如何为hist2d打印添加颜色栏

2024-04-19 15:32:47 发布

您现在位置:Python中文网/ 问答频道 /正文

嗯,当我直接用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'

Tags: import图形normmatplotlibasnpfigplt
1条回答
网友
1楼 · 发布于 2024-04-19 15:32:47

第三个选项就快到了。您必须将一个mappable对象传递给colorbar,以便它知道要给colorbar什么颜色映射和限制。可以是AxesImageQuadMesh

^{}的情况下,在h中返回的元组包含mappable,但也包含一些其他内容

docs开始:

Returns: The return value is (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)

相关问题 更多 >