【问题标题】:Generate a loglog heatmap in MatPlotLib using a scatter data set使用散点数据集在 MatPlotLib 中生成 loglog 热图
【发布时间】:2020-05-25 13:44:27
【问题描述】:

我有一个类似于数据集的二维幂律:

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]],但它只进行仿射变换,比例仍然是线性的而不是对数的。你知道我怎样才能得到热图,但有散点图吗?

【问题讨论】:

  • 你试过用 pcolormesh 代替 imshow 吗?

标签: python matplotlib heatmap


【解决方案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()

输出是:

【讨论】:

    猜你喜欢
    • 2011-01-23
    • 2012-02-04
    • 2017-08-06
    • 2014-05-17
    • 2018-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-12
    相关资源
    最近更新 更多