它无法正常工作的原因是plt.hist2d使用pcolorfast方法,这对于大图像更有效,但不支持对数轴.
要使2D直方图在日志轴上正常工作,您需要使用np.histogram2d和ax.pcolor自己创建.但是,它只是一行额外的代码.
首先,让我们在线性轴上使用指数间隔的二进制位:
import numpy as np
import matplotlib.pyplot as plt
x, y = np.random.random((2, 1000))
x = 10**x
xbins = 10**np.linspace(0, 1, 10)
ybins = np.linspace(0, 1, 10)
fig, ax = plt.subplots()
ax.hist2d(x, y, bins=(xbins, ybins))
plt.show()
好的,一切都很好.让我们看看如果我们让x轴使用对数比例会发生什么:
import numpy as np
import matplotlib.pyplot as plt
x, y = np.random.random((2, 1000))
x = 10**x
xbins = 10**np.linspace(0, 1, 10)
ybins = np.linspace(0, 1, 10)
fig, ax = plt.subplots()
ax.hist2d(x, y, bins=(xbins, ybins))
ax.set_xscale('log') #
plt.show()
请注意,日志缩放似乎已应用,但彩色图像(直方图)未反映它.垃圾桶应该是方形的!它们不是因为pcolorfast创建的艺术家不支持日志轴.
为了解决这个问题,让我们使用np.histogram2d制作直方图(plt.hist2d使用幕后的东西),然后使用支持日志轴的pcolormesh(或pcolor)绘制直方图:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1977)
x, y = np.random.random((2, 1000))
x = 10**x
xbins = 10**np.linspace(0, 1, 10)
ybins = np.linspace(0, 1, 10)
counts, _, _ = np.histogram2d(x, y, bins=(xbins, ybins))
fig, ax = plt.subplots()
ax.pcolormesh(xbins, ybins, counts.T)
ax.set_xscale('log')
plt.show()
(注意,我们必须在此处转置计数,因为pcolormesh期望轴的顺序为(Y,X).)
现在我们得到了我们期望的结果: