我想在我的轴实例(ax1)坐标系中具有任意尺寸的任意位置绘制一个从左到右填充渐变颜色的矩形。

我的第一个想法是创建一个路径补丁,并以某种方式将其填充设置为颜色渐变。但是根据《本报》的报道,这是没有办法的。
接下来,我尝试使用颜色条。我创建了一个第二轴线实例AX2使用fig.add_axes([left, bottom, width, height])并增加了一个颜色条到。
ax2 = fig.add_axes([0, 0, width, height/8])
colors = [grad_start_color, grad_end_color]
index = [0.0, 1.0]
cm = LinearSegmentedColormap.from_list('my_colormap', zip(index, colors))
colorbar.ColorbarBase(ax2, cmap=cm, orientation='horizontal')
Run Code Online (Sandbox Code Playgroud)
但位置参数传递给fig.add_axes()是坐标系中的无花果,并且不与坐标系匹配AX1。
我怎样才能做到这一点?
我一直在问自己一个类似的问题,并花了一些时间寻找答案,最终发现这可以很容易地通过以下方式完成imshow:
from matplotlib import pyplot
pyplot.imshow([[0.,1.], [0.,1.]],
cmap = pyplot.cm.Greens,
interpolation = 'bicubic'
)
Run Code Online (Sandbox Code Playgroud)
可以指定颜色图,使用什么插值等等。我觉得非常有趣的另一件事是可以指定要使用颜色图的哪一部分。这是通过vmin和完成的vmax:
pyplot.imshow([[64, 192], [64, 192]],
cmap = pyplot.cm.Greens,
interpolation = 'bicubic',
vmin = 0, vmax = 255
)
Run Code Online (Sandbox Code Playgroud)
受到这个例子的启发
我选择X = [[0.,1.], [0.,1.]]使渐变从左到右变化。通过将数组设置为类似X = [[0.,0.], [1.,1.]],您可以获得从上到下的渐变。一般情况下,可以在X = [[i00, i01],[i10, i11]]、i00、 中为每个角指定颜色i01,i10并分别为左上角、右上角、左下角和右下角i11指定颜色。增加的大小X显然允许为更具体的点设置颜色。
你解决过这个问题吗?我想要同样的东西,并使用这里的坐标映射找到了答案,
#Map axis to coordinate system
def maptodatacoords(ax, dat_coord):
tr1 = ax.transData.transform(dat_coord)
#create an inverse transversion from display to figure coordinates:
fig = ax.get_figure()
inv = fig.transFigure.inverted()
tr2 = inv.transform(tr1)
#left, bottom, width, height are obtained like this:
datco = [tr2[0,0], tr2[0,1], tr2[1,0]-tr2[0,0],tr2[1,1]-tr2[0,1]]
return datco
#Plot a new axis with a colorbar inside
def crect(ax,x,y,w,h,c,**kwargs):
xa, ya, wa, ha = maptodatacoords(ax, [(x,y),(x+w,y+h)])
fig = ax.get_figure()
axnew = fig.add_axes([xa, ya, wa, ha])
cp = mpl.colorbar.ColorbarBase(axnew, cmap=plt.get_cmap("Reds"),
orientation='vertical',
ticks=[],
**kwargs)
cp.outline.set_linewidth(0.)
plt.sca(ax)
Run Code Online (Sandbox Code Playgroud)
希望这对将来需要类似功能的人有所帮助。我最终使用了补丁对象网格。
| 归档时间: |
|
| 查看次数: |
3920 次 |
| 最近记录: |