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

标签 python matplotlib histogram2d

我只是想知道这是否可以做到。我尝试使用 numpy logspace 显式设置 bins,我还尝试将 xscale 设置为“log”。这些选项都不起作用。有人试过这个吗?

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

最佳答案

它无法正常工作的原因是 plt.hist2d 使用了 pcolorfast 方法,该方法对于大图像更有效,但不支持对数轴。

要获得在对数轴上正确工作的二维直方图,您需要使用 np.histogram2dax.pcolor 自行制作。然而,这只是额外的一行代码。

首先,让我们在线性轴上使用指数间隔的 bin:

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

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

关于python - 使用 hist2d 在 matplotlib 中创建对数线性图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29175093/

相关文章:

python - 如何提高 matplotlib 图像质量?

python - Pandas /Python : 2D histogram fails with value error

matlab - 为二维直方图添加半透明

python - 正则表达式命名组以开头但不以结尾

python - 错误 : sqlite3. 操作错误 : no such table: main. m

python-3.x - matplotlib 图例仅基于线条样式而不是颜色

python - 使用带有手动分箱的 Python 绘制直方图

c++ - 我可以对 Java 或 C++ 使用 Python 缩进样式吗?

python - 客户端s3上传并返回图像的公共(public)url

python - 使 plt.colorbar 扩展到 vmin/vmax 前后的步骤