Tho*_*ius 18 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 works
plt.figure()
plt.hist2d(x, y, bins=40, norm=LogNorm())
plt.colorbar()
Run Code Online (Sandbox Code Playgroud)
但是为什么以下不起作用,我需要添加什么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'
Run Code Online (Sandbox Code Playgroud)
tmd*_*son 22
你几乎有第三种选择.您必须传递一个mappable对象,colorbar以便知道为色条提供什么颜色图和限制.这可以是一个AxesImage或QuadMesh等
在这种情况下hist2D,元组返回你的h包含mappable,但也有一些其他的东西.
来自文档:
返回: 返回值为(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())
plt.colorbar(h[3], ax=ax)
Run Code Online (Sandbox Code Playgroud)
或者:
counts, xedges, yedges, im = ax.hist2d(x, y, bins=40, norm=LogNorm())
plt.colorbar(im, ax=ax)
Run Code Online (Sandbox Code Playgroud)