matplotlib: 如何在2D直方图中指定颜色级别?

6
我想绘制一个包含正数和负数的2D直方图。我有以下使用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')

enter image description here

2个回答

6
感谢 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()

enter image description here


0

添加vminvmax参数,使它们的绝对值相等

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

看看你是否喜欢结果

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接