我正在尝试创建一个包含matplotlib
的图,该图包括人为偏移的几条不同的线,这些线根据RedBlue色图mpl.cm.RdBu
进行了着色。现在,我想要在绘图旁边有一个箭头,可以用作有效的色标,这意味着它应该具有颜色渐变。
到目前为止,我已经设法在this answer的帮助下使用annotate
创建了箭头本身,并使用this brilliant answer在图中绘制了一个“彩虹箭头”(注意:需要matplotlib 2.2.4
或更早版本才能运行此部分代码,请参见注释。)
这是我到目前为止可以生产的MWE:
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.transforms
import matplotlib.path
from matplotlib.collections import LineCollection
# from https://stackoverflow.com/questions/47163796/using-colormap-with-annotate-arrow-in-matplotlib
def rainbowarrow(ax, start, end, cmap="viridis", n=50,lw=3):
cmap = plt.get_cmap(cmap,n)
# Arrow shaft: LineCollection
x = np.linspace(start[0],end[0],n)
y = np.linspace(start[1],end[1],n)
points = np.array([x,y]).T.reshape(-1,1,2)
segments = np.concatenate([points[:-1],points[1:]], axis=1)
lc = LineCollection(segments, cmap=cmap, linewidth=lw)
lc.set_array(np.linspace(0,1,n))
ax.add_collection(lc)
# Arrow head: Triangle
tricoords = [(0,-0.4),(0.5,0),(0,0.4),(0,-0.4)]
angle = np.arctan2(end[1]-start[1],end[0]-start[0])
rot = matplotlib.transforms.Affine2D().rotate(angle)
tricoords2 = rot.transform(tricoords)
tri = matplotlib.path.Path(tricoords2, closed=True)
ax.scatter(end[0],end[1], c=1, s=(2*lw)**2, marker=tri, cmap=cmap,vmin=0)
ax.autoscale_view()
def plot_arrow(data,n):
fig, subfig = plt.subplots(1,1,figsize=(6.28,10)) # plotsize, etc
colorP=mpl.cm.RdBu(0.2)
i = 0
while i<=n-1:
subfig.plot(data[i,0], (data[i,1])+i, lw=2, color=mpl.cm.RdBu(1-i/20)) # plot of data
i=i+1
subfig.annotate('', xy=(1.1,0), xycoords='axes fraction', xytext=(1.1,1),
arrowprops=dict(arrowstyle="<-", lw = 3))
subfig.annotate('A', xy=(1.1,0), xycoords='axes fraction', xytext=(1.1,1))
subfig.annotate('B', xy=(1.1,0), xycoords='axes fraction', xytext=(1.1,0))
rainbowarrow(subfig, (1.1,3), (1.1,5), cmap='RdBu_r', n=100,lw=3)
plt.show(fig)
plt.close(fig)
# things to plot
np.random.seed(19680802)
n = 20
i = 0
data = np.empty([n,2,10])
while i<=n-1:
data[i]=np.sin(np.random.rand(10))
i = i+1
# actual plot
plot_arrow(data,n)
以下是生成的图形:
简而言之:我希望绘图外的注释箭头具有颜色图的颜色,就像绘图内的小彩虹箭头一样。