gpt4 book ai didi

python - 如何为 hist2d 图添加颜色条

转载 作者:IT老高 更新时间:2023-10-28 21:12:24 32 4
gpt4 key购买 nike

好吧,当我直接使用 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'

最佳答案

使用第 3 个选项,您就快到了。您必须将 mappable 对象传递给 colorbar 以便它知道给颜色条的颜色图和限制。可以是 AxesImageQuadMesh 等。

hist2D 的情况下,您的 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)

关于python - 如何为 hist2d 图添加颜色条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42387471/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com