[英]Matplotlib Rectangle With Color Gradient Fill
我想在我的轴实例( 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')
但是传递给fig.add_axes()
的位置参数在fig的坐标系中,并且与ax1的坐标系不匹配。
我怎样才能做到这一点?
我一直在问自己一个类似的问题,并花了一些时间寻找答案,最终发现imshow
可以很容易地做到这imshow
:
from matplotlib import pyplot
pyplot.imshow([[0.,1.], [0.,1.]],
cmap = pyplot.cm.Greens,
interpolation = 'bicubic'
)
可以指定颜色图,要使用的插值等等。 我发现非常有趣的另一件事是可以指定要使用的色图部分。 这是通过vmin
和vmax
来完成的:
pyplot.imshow([[64, 192], [64, 192]],
cmap = pyplot.cm.Greens,
interpolation = 'bicubic',
vmin = 0, vmax = 255
)
受此示例启发
我选择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)
希望这对将来需要类似功能的任何人有所帮助。 我结束了使用补丁的网格物体代替 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.