【问题标题】:Matplotlib Rectangle With Color Gradient Fill带有颜色渐变填充的 Matplotlib 矩形
【发布时间】:2014-07-26 23:33:30
【问题描述】:

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

我的第一个想法是创建一个路径补丁并以某种方式将其填充设置为颜色渐变。但根据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的坐标系不匹配。

我该怎么做?

【问题讨论】:

标签: python matplotlib


【解决方案1】:

我一直在问自己一个类似的问题,并花了一些时间寻找答案,最终发现imshow可以很容易地做到这一点:

from matplotlib import pyplot

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

可以指定颜色图、使用什么插值等等。我发现非常有趣的另一件事是可以指定要使用颜色图的哪一部分。这是通过vminvmax 完成的:

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

灵感来自this example


补充说明:

我选择了X = [[0.,1.], [0.,1.]],让渐变从左到右变化。通过将数组设置为X = [[0.,0.], [1.,1.]] 之类的值,您可以获得从上到下的渐变。一般来说,可以为每个角指定颜色,其中X = [[i00, i01],[i10, i11]]i00i01i10i11 指定左上角、右上角、左下角和分别是右下角。增加X 的大小显然可以为更具体的点设置颜色。

【讨论】:

  • 还有一点注意:如果你以后想设置xlim/ylim,你可能需要使用参数aspect = 'auto'...
【解决方案2】:

你解决过这个问题吗?我想要同样的东西,并使用来自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

【讨论】:

    猜你喜欢
    • 2023-03-19
    • 2018-08-30
    • 1970-01-01
    • 2015-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多