简体   繁体   中英

matplotlib: How can you specify colour levels in a 2D historgram

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 (ie, I want my colorbar to be symmetric around zero). I've also tried imshow.

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.

Any advice would be greatly appreciated.

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')

在此处输入图片说明

Thanks to 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()

在此处输入图片说明

Add vmin and vmax parameters with equal absolute values

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

and see if you like the result

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM