I want to do something similar to http://matplotlib.org/examples/pylab_examples/hist2d_log_demo.html but I\'ve read that using pylab for code other than in python interactiv
A colorbar needs a ScalarMappable object as its first argument. plt.hist2d
returns this as the forth element of the returned tuple.
h = hist2d(x, y, bins=40, norm=LogNorm())
colorbar(h[3])
Complete code:
from matplotlib.colors import LogNorm
import matplotlib.pyplot as plt
import numpy as np
#normal distribution center at x=0 and y=5
x = np.random.randn(100000)
y = np.random.randn(100000)+5
h = plt.hist2d(x, y, bins=40, norm=LogNorm())
plt.colorbar(h[3])
show()
This should do it:
from matplotlib.colors import LogNorm
import matplotlib.pyplot as plt
from numpy.random import randn
#normal distribution center at x=0 and y=5
x = randn(100000)
y = randn(100000)+5
H, xedges, yedges, img = plt.hist2d(x, y, norm=LogNorm())
extent = [yedges[0], yedges[-1], xedges[0], xedges[-1]]
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
im = ax.imshow(H, cmap=plt.cm.jet, extent=extent, norm=LogNorm())
fig.colorbar(im, ax=ax)
plt.show()
Notice how colorbar is attached to "fig", not "sub_plot". There are some other examples of this here. Notice how you also need to generate a ScalarMappable with imshow
, as explained in the API here.