Python matplotlib:如何在二维直方图中指定颜色级别
我想画一个二维直方图,包括正数和负数。我有以下使用pcolormesh的代码,但我无法指定强制白色对应于零的颜色级别(即,我希望我的颜色条在零附近对称)。我也尝试过imshow 我知道你可以在plt.contour和plt.contourf中指定颜色级别,但我找不到一种使用块绘制2D直方图的方法 如有任何建议,将不胜感激Python matplotlib:如何在二维直方图中指定颜色级别,python,numpy,matplotlib,histogram,Python,Numpy,Matplotlib,Histogram,我想画一个二维直方图,包括正数和负数。我有以下使用pcolormesh的代码,但我无法指定强制白色对应于零的颜色级别(即,我希望我的颜色条在零附近对称)。我也尝试过imshow 我知道你可以在plt.contour和plt.contourf中指定颜色级别,但我找不到一种使用块绘制2D直方图的方法 如有任何建议,将不胜感激 import numpy as np import matplotlib.pyplot as plt from matplotlib import cm as CM fig
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')
多亏了
添加具有相等绝对值的
vmin
和vmax
参数
plt.pcolormesh(xedges, yedges, Z, cmap=CM.RdBu_r, vmin=-7, vmax=7)
看看你是否喜欢这个结果
plt.pcolormesh(xedges, yedges, Z, cmap=CM.RdBu_r, vmin=-7, vmax=7)