【问题标题】:How to add a colorbar for a hist2d plot如何为 hist2d 图添加颜色条
【发布时间】:2021-08-15 03:11:22
【问题描述】:

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

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

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

    hist2D 的情况下,h 中返回的元组包含 mappable,但也包含其他一些内容。

    来自docs

    返回: 返回值为 (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)
    

    【讨论】:

    • fig.colorbar(im) 也有效,并且似乎与答案的其余部分更加一致。
    • @ThomasH ,您的建议还可以在 Jupyter 笔记本中提供更连贯的输出
    猜你喜欢
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    • 1970-01-01
    • 2015-08-16
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    相关资源
    最近更新 更多