【问题标题】:How do I set limits on ticks, colors, and labels for colorbar contourf matplotlib如何为 colorbar contourf matplotlib 设置刻度、颜色和标签的限制
【发布时间】:2016-05-04 23:30:48
【问题描述】:

我有一个值的空间字段,我在一天中定期输出。我正在使用contourf 进行绘图,并且我想在当天的数据过程中执行以下操作:

  • 将 colobar 上的颜色限制为代表当天数据的最小值和最大值的值
  • 在 24 小时图上保持颜色条在天数数据的最大值和最小值处保持静态
  • 在这 24 小时内保持标签不变

例如:

data = np.random.uniform(0, 5, size=(24,30,30))
data[3,:,:]=np.random.uniform(1,3,size=(30,30))  # example of bad plot
fgsize=(12,4)
numrecs = np.size(data,axis=0)
cbar_min = np.min(data)
cbar_max = np.max(data)
cbarlabels = np.linspace(np.floor(cbar_min), np.ceil(cbar_max), num=5, endpoint=True)


for tt in range(0, numrecs):
    plt.figure(figsize=fgsize, dpi=80)
    plt.title('this is a title')
    plt.contourf(data[tt, :, :], 35, vmin=cbar_min, vmax=cbar_max, cmap='coolwarm')
    cbar =plt.colorbar()
    cbar.set_ticks(cbarlabels)
    cbar.set_ticklabels(cbarlabels)
    cbar.set_label('my data has units')
    plt.show()
    plt.close()

这是bad plot 的示例。颜色似乎有限,但颜色条改变了它的颜色/标签限制。我该如何解决?

这是good plot 的示例。

【问题讨论】:

    标签: python matplotlib colorbar


    【解决方案1】:

    事实证明,contourf 在设置颜色图的级别时有点棘手,请参阅this answer。您可以通过对轮廓进行归一化来获得适当的限制和颜色,如下所示:

    import numpy as np
    import matplotlib.pyplot as plt
    
    data = np.random.uniform(0, 5, size=(24,30,30))
    data[3,:,:]=np.random.uniform(1,3,size=(30,30))  # example of bad plot
    fgsize=(12,4)
    numrecs = np.size(data,axis=0)
    cbar_min = np.min(data)
    cbar_max = np.max(data)
    cbarlabels = np.linspace(np.floor(cbar_min), np.ceil(cbar_max), num=5, endpoint=True)
    
    # Set the normalisation for 35 levels (as in your example)
    import matplotlib.colors as mc
    levels = np.linspace(np.floor(cbar_min), np.ceil(cbar_max), 35) # to draw 35 levels
    norm = mc.BoundaryNorm(levels, 256)
    
    for tt in range(0, numrecs):
        print cbar_min, cbar_max
        plt.figure(figsize=fgsize, dpi=80)
        plt.title('this is a title')
    
        # Draw those levels, with proper normalisation, here:
        plt.contourf(data[tt, :, :], levels, vmin=cbar_min, vmax=cbar_max, cmap='coolwarm', levels=levels, norm=norm)
    
        cbar = plt.colorbar()
        cbar.set_ticks(cbarlabels)
        cbar.set_ticklabels(cbarlabels)
        cbar.set_label('my data has units')
        plt.show()
    

    【讨论】:

    • 感谢实验室,我在您的帮助下解决了这个问题。它对绘图进行了奇怪的数字限制,而没有相应地向下/向上舍入 cbar_min cbar_max。但它是固定的!非常感谢
    • @SBFRF 很高兴我能帮上忙!如果你喜欢这个答案,你介意接受吗?
    猜你喜欢
    • 2018-06-03
    • 1970-01-01
    • 2011-09-23
    • 2020-06-04
    • 2016-02-19
    • 2018-10-06
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    相关资源
    最近更新 更多