【问题标题】:matplotlib: How can you specify colour levels in a 2D historgrammatplotlib:如何在 2D 直方图中指定颜色级别
【发布时间】:2015-02-03 23:32:33
【问题描述】:

我想绘制一个包含正数和负数的二维直方图。我有以下使用 pcolormesh 的代码,但我无法指定颜色级别以强制白色对应于零(即,我希望我的颜色条围绕零对称)。我也试过 imshow。

我知道您可以在 plt.contour 和 plt.contourf 中指定颜色级别,但我找不到使用块绘制 2D 直方图的方法。

任何建议将不胜感激。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm as CM

fig = plt.figure()

# create an example histogram which is asymmetrical around zero
x = np.random.rand(400)
y = np.random.rand(400)    
Z, xedges, yedges = np.histogram2d(x, y, bins=10)   
Z = Z - 2.

plt.pcolormesh(xedges, yedges, Z, cmap=CM.RdBu_r)

plt.colorbar()
plt.savefig('test.png')

【问题讨论】:

    标签: python numpy matplotlib histogram


    【解决方案1】:

    感谢http://nbviewer.ipython.org/gist/pelson/5628989

    import matplotlib.pyplot as plt
    import numpy as np
    from matplotlib.colors import from_levels_and_colors
    
    x = np.random.rand(400)
    y = np.random.rand(400)
    Z, xedges, yedges = np.histogram2d(x, y, bins=10)
    Z = Z - 2.
    #  -1 0 3 6 9
    cmap, norm = from_levels_and_colors([-1, 0, 3, 6, 9, 12], ['r', 'b', 'g', 'y', 'm']) # mention levels and colors here
    plt.pcolormesh(xedges, yedges, Z, cmap=cmap, norm=norm)
    plt.colorbar()
    plt.show()
    

    【讨论】:

      【解决方案2】:

      添加绝对值相等的vminvmax参数

      plt.pcolormesh(xedges, yedges, Z, cmap=CM.RdBu_r, vmin=-7, vmax=7)
      

      看看你喜不喜欢这个结果

      【讨论】:

        猜你喜欢
        • 2017-06-29
        • 1970-01-01
        • 1970-01-01
        • 2013-12-24
        • 2018-02-09
        • 1970-01-01
        • 2015-10-22
        • 2022-01-09
        • 2019-10-31
        相关资源
        最近更新 更多