使用散点数据集在MatPlotLib中生成对数热图

时间:2020-05-25 13:44:27

标签: python matplotlib heatmap

我有一个像数据集一样的二维幂律:

import numpy as np
X = 1 / np.random.power(2, size=1000)
Y = 1 / np.random.power(2, size=1000)

我可以使用对数标度的散点图进行绘制

import matplotlib.pyplot as plt
plt.figure()
plt.scatter(X, Y, alpha=0.3)
plt.loglog()
plt.show()

获取:

enter image description here

但是,它不能正确显示密度高的原点附近的数据。因此,我将此图转换为热图。我做到了:

from matplotlib.colors import LogNorm
heatmap, xedges, yedges = np.histogram2d(X, Y, bins=np.logspace(0, 2, 30))
plt.figure()
plt.imshow(heatmap.T, origin='lower', norm=LogNorm())
plt.colorbar()
plt.show()

获取:

enter image description here

该图看起来不错,但轴刻度线不好。为了更改比例,我尝试在extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]中添加imshow,但是它仅进行仿射变换,比例仍然是线性的而不是对数的。您知道我如何获得热图图,但有一点点滴答声吗?

1 个答案:

答案 0 :(得分:0)

您可以按照JohanC的建议使用pcolormesh

以下是您使用pcolormesh进行编码的示例:

import numpy as np
import matplotlib.pyplot as plt

X = 1 / np.random.power(2, size=1000)
Y = 1 / np.random.power(2, size=1000)

heatmap, xedges, yedges = np.histogram2d(X, Y, bins=np.logspace(0, 2, 30))

fig = plt.figure()
ax = fig.add_subplot(111)

ax.pcolormesh(xedges, yedges, heatmap)
ax.loglog()
ax.set_xlim(1, 50)
ax.set_ylim(1, 50)

plt.show()

输出为:

enter image description here

相关问题