Matplotlib带有颜色渐变填充的矩形

8

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

enter image description here

我的第一个想法是创建一个路径补丁,并以某种方式将其填充为颜色渐变。但根据此帖子,没有一种方法可以做到这一点。

接下来我尝试使用颜色条。我使用fig.add_axes([left, bottom, width, height])创建了第二个轴实例ax2,并向其中添加了一个颜色条。

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 的坐标系不匹配。

我该怎么做呢?


我从未使用过它,但也许这可以帮助您将坐标从ax1重新计算到fig:Transformations Tutorial - Matplotlib 1.3.1 documentation - furas
2个回答

9

我曾经问过自己一个类似的问题,并花了一些时间寻找答案,最终发现这可以通过imshow轻松实现:

from matplotlib import pyplot

pyplot.imshow([[0.,1.], [0.,1.]], 
  cmap = pyplot.cm.Greens, 
  interpolation = 'bicubic'
)

enter image description here

可以指定一个色图,选择使用的插值方式等等。另外一个非常有趣的功能是可以指定使用色图的哪个部分,这可以通过vminvmax实现:

pyplot.imshow([[64, 192], [64, 192]], 
  cmap = pyplot.cm.Greens, 
  interpolation = 'bicubic', 
  vmin = 0, vmax = 255
)

enter image description here

这个例子启发


附加说明:

我选择 X = [[0.,1.], [0.,1.]] 使得渐变从左到右变化。如果将数组设置为类似 X = [[0.,0.], [1.,1.]] 的内容,则会得到从上到下的渐变效果。一般来说,可以为每个角指定颜色,在 X = [[i00, i01],[i10, i11]] 中,i00i01i10i11 分别指定左上角、右上角、左下角和右下角的颜色。增加 X 的大小显然可以为更具体的点设置颜色。


另外一点需要注意的是:如果您想在将来设置xlim/ylim,您可能希望使用参数aspect='auto' - Mr Tsjolder

2

你解决了这个问题吗?我也想要同样的东西,并且在这里使用坐标映射找到答案。

 #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)

希望这对需要类似功能的人有所帮助。我最终使用了一组补丁对象的网格而不是其他方法。 链接

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接