作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
好吧,当我直接使用 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
以便它知道给颜色条的颜色图和限制。可以是 AxesImage
或 QuadMesh
等。
在 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/
我是一名优秀的程序员,十分优秀!