Matplotlib矩形与颜色渐变填充

时间:2014-07-26 23:33:30

标签: python matplotlib

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

enter image description here

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

接下来我尝试使用彩条。我使用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 的坐标系不匹配

我该怎么做?

2 个答案:

答案 0 :(得分:3)

我一直在问自己一个类似的问题,并花了一些时间寻找答案,最终发现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

this example启发

附加说明:

我选择X = [[0.,1.], [0.,1.]]从左到右进行渐变。通过将数组设置为X = [[0.,0.], [1.,1.]],您可以从上到下获得渐变。通常,可以为X = [[i00, i01],[i10, i11]]i00i01i10i11指定上方的每个角落指定颜色。分别是左,右上,左下和右下角。增加X的大小显然可以为更具体的点设置颜色。

答案 1 :(得分:1)

你有没有解决过这个问题?我想要同样的事情,并使用here

的坐标映射找到答案
 #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)

希望这可以帮助将来需要类似功能的人。我最终使用了一个补丁对象网格instead

相关问题