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 interactive mode is bad practice so I'd like to do this with matplotlib.pyplot. However, I can't figure out how to make this code work using pyplot. Using, pylab, the example given is
from matplotlib.colors import LogNorm
from pylab import *
#normal distribution center at x=0 and y=5
x = randn(100000)
y = randn(100000)+5
hist2d(x, y, bins=40, norm=LogNorm())
colorbar()
show()
I've tried a lot like
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
h1 = ax1.hist2d([1,2],[3,4])
and from here I've tried everything from plt.colorbar(h1)
plt.colorbar(ax1)
plt.colorbar(fig)
ax.colorbar()
etc etc and I can't get anything to work.
In general, I'm honestly not really clear on the relationship between pylab and pyplot, even after reading http://matplotlib.org/faq/usage_faq.html. For example show()
in pylab seems to become plt.show()
in pyplot, but for some reason colorbar
doesn't become plt.colorbar()
?
For example,
You can change the color of bars in a barplot using color argument. RGB is a way of making colors. You have to to provide an amount of red, green, blue, and the transparency value to the color argument and it returns a color.
will map the data in Z linearly from -1 to +1, so Z=0 will give a color at the center of the colormap RdBu_r (white in this case). Matplotlib does this mapping in two steps, with a normalization from the input data to [0, 1] occurring first, and then mapping onto the indices in the colormap.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With