使用散点数据集在 MatPlotLib 中生成 loglog 热图
Generate a loglog heatmap in MatPlotLib using a scatter data set
我有一个类似于数据集的二维幂律:
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()
获得:
但是,它不能正确显示密度高的原点附近的数据。因此,我在热图中转换了这个图。我这样做了:
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()
获得:
情节看起来不错,但坐标轴刻度不好。要更改比例,我尝试在 imshow
中添加 extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
但它只进行仿射变换,比例仍然是线性的而不是对数的。你知道我怎样才能得到热图图但有散点图吗?
您可以按照 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()
输出为:
我有一个类似于数据集的二维幂律:
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()
获得:
但是,它不能正确显示密度高的原点附近的数据。因此,我在热图中转换了这个图。我这样做了:
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()
获得:
情节看起来不错,但坐标轴刻度不好。要更改比例,我尝试在 imshow
中添加 extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
但它只进行仿射变换,比例仍然是线性的而不是对数的。你知道我怎样才能得到热图图但有散点图吗?
您可以按照 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()
输出为: