Well, I know how to add a colour bar to a figure, when I have created the figure directly with matplotlib.pyplot.plt
.
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
# This works
plt.figure()
plt.hist2d(x, y, bins=40, norm=LogNorm())
plt.colorbar()
But why does the following not work, and what would I need to add to the call of colorbar(..)
to make it work.
fig, ax = plt.subplots()
ax.hist2d(x, y, bins=40, norm=LogNorm())
fig.colorbar()
# TypeError: colorbar() missing 1 required positional argument: 'mappable'
fig, ax = plt.subplots()
ax.hist2d(x, y, bins=40, norm=LogNorm())
fig.colorbar(ax)
# AttributeError: 'AxesSubplot' object has no attribute 'autoscale_None'
fig, ax = plt.subplots()
h = ax.hist2d(x, y, bins=40, norm=LogNorm())
plt.colorbar(h, ax=ax)
# AttributeError: 'tuple' object has no attribute 'autoscale_None'
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…