如何为hist2d图添加颜色条 [英] How to add a colorbar for a hist2d plot
问题描述
好吧,当我直接使用 matplotlib.pyplot.plt
创建图形时,我知道如何向图形添加颜色条.
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()
但是以下原因为何不起作用,我需要在 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'
推荐答案
第三个选项就快到了.您必须将 mappable
对象传递给 colorbar
,这样它才能知道要提供colorbar的颜色图和限制.可以是 AxesImage
或 QuadMesh
等.
You are almost there with the 3rd option. You have to pass a mappable
object to colorbar
so it knows what colormap and limits to give the colorbar. That can be an AxesImage
or QuadMesh
, etc.
对于 hist2D
,在您的 h
中返回的元组包含该 mappable
,也包含其他一些内容.
In the case of hist2D
, the tuple returned in your h
contains that mappable
, but also some other things too.
来自文档:
退货:返回值为 (counts, xedges, yedges, Image).
Returns: The return value is (counts, xedges, yedges, Image).
因此,要制作颜色条,我们只需要 Image
.
So, to make the colorbar, we just need the Image
.
要修改您的代码,请执行以下操作:
To fix your code:
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)
这篇关于如何为hist2d图添加颜色条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!