【问题标题】:Do matplotlib.contourf levels depend on the amount of colors in the colormap?matplotlib.contourf 级别是否取决于颜色图中的颜色数量?
【发布时间】:2025-12-01 17:25:01
【问题描述】:

我正在使用contourf 绘制地图,我通常会使用levels = 50 的默认(彩虹)颜色方案。

#Various imports
#LOTS OF OTHER CODE BEFORE
plot = plt.contourf(to_plot, 50)
plt.show()
#LOTS OF OTHER CODE AFTER

输出如下。我做了各种其他的事情来获得海岸线等。如果有人感兴趣的话,它是使用 iris 和 cartopy 完成的。

现在我决定不想使用彩虹方案,所以我使用了一些 Cyntia Brewer 颜色:

brewer_cmap = mpl.cm.get_cmap('brewer_Reds_09')
plot = iplt.contourf(to_plot, 50, cmap=brewer_cmap) # expect 50 levels

但是输出是:

您可以看到Here 这个调色板只有 9 种颜色。所以我的问题是,contourf 级别是否受颜色图中可用颜色数量的限制?我非常喜欢这张地图,我想知道是否可以生成一张类似它但红色级别更高的新地图?

我对能够捕获数据的可变性很感兴趣,因此更多的轮廓级别似乎是个好主意,但我热衷于放弃彩虹方案,而只使用基于单一颜色的方案。

干杯!

【问题讨论】:

    标签: python matplotlib colorbrewer


    【解决方案1】:

    是的,它是一个离散的颜色图,如果您想要一个连续的,您需要制作一个自定义的颜色图。

    #the colormap data can be found here: https://github.com/SciTools/iris/blob/master/lib/iris/etc/palette/sequential/Reds_09.txt
    
    In [22]:
    
    %%file temp.txt
    1.000000 0.960784 0.941176
    0.996078 0.878431 0.823529
    0.988235 0.733333 0.631373
    0.988235 0.572549 0.447059
    0.984314 0.415686 0.290196
    0.937255 0.231373 0.172549
    0.796078 0.094118 0.113725
    0.647059 0.058824 0.082353
    0.403922 0.000000 0.050980
    Overwriting temp.txt
    In [23]:
    
    c_array = np.genfromtxt('temp.txt')
    from matplotlib.colors import LinearSegmentedColormap
    plt.register_cmap(name='Test', data={key: tuple(zip(np.linspace(0,1,c_array.shape[0]), c_array[:,i], c_array[:,i])) 
                                             for key, i in zip(['red','green','blue'], (0,1,2))})
    In [24]:
    
    plt.contourf(X, Y, Z, 50, cmap=plt.get_cmap('Test'))
    plt.colorbar()
    Out[24]:
    <matplotlib.colorbar.Colorbar instance at 0x108948320>
    

    【讨论】:

    • 干杯,这回答了我的问题。不过有 1 件事,请您解释一下这是做什么的:data={key: tuple(zip(np.linspace(0,1,c_array.shape[0]), c_array[:,i], c_array[:,i])) for key, i in zip(['red','green','blue'], (0,1,2))} 恐怕我的 Python 不是那么强大 :)。
    • {} 之间的部分称为字典理解。基本上它会生成一个字典来生成colormap。请参阅:matplotlib.org/examples/pylab_examples/custom_cmap.html,了解该字典的外观。干杯!