Matplotlib 矩形带颜色渐变填充

9 投票
2 回答
9222 浏览
提问于 2025-04-18 14:54

我想在我的坐标系统(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的坐标系统不匹配。

那我该怎么做呢?

2 个回答

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)

希望这能帮助将来需要类似功能的朋友。我最后使用了一组补丁对象的网格,而不是其他方法

9

我也曾经在想类似的问题,并花了一些时间寻找答案,最后发现其实可以很简单地通过imshow来实现:

from matplotlib import pyplot

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

在这里输入图片描述

你可以指定颜色映射(colormap)、使用什么样的插值方法等等。有一点我觉得特别有趣,就是可以指定使用颜色映射的哪一部分。这是通过vminvmax来实现的:

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]]中,i00i01i10i11分别指定左上角、右上角、左下角和右下角的颜色。显然,增大X的大小可以让你为更多的具体点设置颜色。

撰写回答