如何为hist2d图添加色条

37

我知道如何在使用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()

但是为什么下面的代码不起作用,我需要在调用colorbar(..)时添加什么东西才能使它起作用呢?

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'
1个回答

51

你已经接近第三个选项了。你需要传递一个可映射的对象给colorbar,这样它就知道要给颜色条提供什么颜色和限制。这可以是AxesImageQuadMesh等。

hist2D的情况下,你的h返回的元组包含了那个mappable,但也包含其他一些东西。

根据文档

返回值: 返回值为(counts, xedges, yedges, Image)。

所以,我们只需要Image来创建颜色条。

修复你的代码:

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

fig, ax = plt.subplots()
h = ax.hist2d(x, y, bins=40, norm=LogNorm())
fig.colorbar(h[3], ax=ax)

或者:

counts, xedges, yedges, im = ax.hist2d(x, y, bins=40, norm=LogNorm())
fig.colorbar(im, ax=ax)

3
fig.colorbar(im) 也可以运行,并且似乎更符合答案的其余部分。 - ThomasH
@ThomasH,您的建议还可以在Jupyter笔记本中产生更连贯的输出。 - Nathan Musoke

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接