问题描述
我想绘制一个包含正数和负数的2D直方图.我有以下使用pcolormesh的代码,但是我无法指定颜色级别来强制白色对应于零(即我希望我的颜色条在零附近对称).我也尝试过imshow.
I would like to plot a 2D histogram that includes both positive and negative numbers. I have the following code which uses pcolormesh but I am unable to specify the color levels to force the white color to corresponds to zero (i.e., I want my colorbar to be symmetric around zero). I've also tried imshow.
我知道您可以在plt.contour和plt.contourf中指定颜色级别,但是我找不到使用块绘制2D直方图的方法.
I know you can specify colour levels in plt.contour and plt.contourf but I can't find a way to plot the 2D histogram using blocks.
任何建议将不胜感激.
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
参数
Add vmin
and vmax
parameters with equal absolute values
plt.pcolormesh(xedges, yedges, Z, cmap=CM.RdBu_r, vmin=-7, vmax=7)
看看您是否喜欢结果
这篇关于matplotlib:如何在2D历史图中指定颜色级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!