使用hist2d在matplotlib中创建对数线性图

时间:2015-03-20 20:14:00

标签: python matplotlib histogram2d

我只是想知道是否可以这样做。我试图使用numpy logspace显式设置bin,我也尝试将xscale设置为'log'。这些选项都不起作用。有没人试过这个?

我只想要一个带有对数x轴和线性y轴的二维直方图。

1 个答案:

答案 0 :(得分:14)

它无法正常工作的原因是plt.hist2d使用pcolorfast方法,这对大图像效率更高,但不支持日志轴。

要使二维直方图在日志轴上正常工作,您需要使用np.histogram2dax.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()

enter image description here

好的,一切都很好。让我们看看如果我们让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') # <-- Only difference from previous example

plt.show()

enter image description here

请注意,似乎已应用日志缩放,但彩色图像(直方图)未反映它。垃圾桶应该是方形的!它们不是因为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()

(请注意,我们必须在此转置counts,因为pcolormesh期望轴的顺序为(Y,X)。)

现在我们得到了我们期望的结果:

enter image description here