Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何为hist2d打印添加颜色栏_Python_Matplotlib - Fatal编程技术网

Python 如何为hist2d打印添加颜色栏

Python 如何为hist2d打印添加颜色栏,python,matplotlib,Python,Matplotlib,嗯,当我直接用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

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

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

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

从:

返回: 返回值为(计数、xedges、yedges、图像)

所以,要制作颜色条,我们只需要
图像

要修复代码,请执行以下操作:

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 noteboook中也提供了更连贯的输出