Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 (i.e., 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')

enter image description here

like image 686
shclim Avatar asked Dec 05 '14 17:12

shclim


1 Answers

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

enter image description here

like image 197
Kirubaharan J Avatar answered Nov 07 '22 12:11

Kirubaharan J