使用散点数据集python matplotlib的热图

时间:2012-01-06 18:26:55

标签: matplotlib heatmap scatter-plot

我正在编写一个脚本,为二维上的散点图数据制作热图。以下是我想要做的一个玩具示例:

import numpy as np
from matplotlib.pyplot import*
x = [1,2,3,4,5]
y = [1,2,3,4,5]
heatmap, xedges, yedges = np.histogram2d(x, y, bins=50)
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
imshow(heatmap, extent = extent)

我应该期望“最温暖的”区域沿着y = x但是它们沿着y = -x + 5出现,即热图在反方向上读取一个列表。我不确定为什么会这样。有什么建议吗?

由于

2 个答案:

答案 0 :(得分:3)

尝试imshow参数origin=lower。默认情况下,它会在左上角设置数组的(0,0)元素。

例如:

import numpy as np
import matplotlib.pyplot as plt
x = [1,2,3,4,5,5]
y = [1,2,3,4,5,5]
heatmap, xedges, yedges = np.histogram2d(x, y, bins=10)
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax1.imshow(heatmap, extent = extent)
ax1.set_title("imshow Default");
ax2 = fig.add_subplot(212)
ax2.imshow(heatmap, extent = extent,origin='lower')
ax2.set_title("imshow origin='lower'");

fig.savefig('heatmap.png')

产地:

enter image description here

答案 1 :(得分:0)

使热图的外观与散点图中的内容保持一致,实际使用:

ax2.imshow(heatmap.T, extent = extent,origin='lower')