根据 Python 中的坐标和大小创建 Density/Heatmap 图

Creating Density/Heatmap Plot from Coordinates and Magnitude in Python

我有一些数据是 5x10 网格上每个点的读数数,格式为;

X = [1, 2, 3, 4,..., 5]
Y = [1, 1, 1, 1,...,10]
Z = [9,8,14,0,89,...,0]

我想将其绘制为上面的 heatmap/density 地图,但我发现的所有 matplotlib 图(包括 contourf)都需要 Z 和 I 的二维数组不明白为什么。

编辑;

我现在已经收集了我想要绘制的实际坐标,它们不像我上面的那样规则;

X = [8,7,7,7,8,8,8,9,9.5,9.5,9.5,11,11,11,10.5,
     10.5,10.5,10.5,9,9,8, 8,8,8,6.5,6.5,1,2.5,4.5,
     4.5,2,2,2,3,3,3,4,4.5,4.5,4.5,4.5,3.5,2.5,2.5,
     1,1,1,2,2,2]

Y = [5.5,7.5,8,9,9,8,7.5,6,6.5,8,9,9,8,6.5,5.5,
      5,3.5,2,2,1,2,3.5,5,1,1,2,4.5,4.5,4.5,4,3,
      2,1,1,2,3,4.5,3.5,2.5,1.5,1,5.5,5.5,6,7,8,9,
      9,8,7]

z = [286,257,75,38,785,3074,1878,1212,2501,1518,419,33,
     3343,1808,3233,5943,10511,3593,1086,139,565,61,61,
     189,155,105,120,225,682,416,30632,2035,165,6777,
     7223,465,2510,7128,2296,1659,1358,204,295,854,7838,
     122,5206,6516,221,282]

据我了解,您不能在 np.array 中使用浮点数,因此我尝试将所有值乘以 10,以便它们都是整数,但我仍然 运行问题。我在尝试做一些行不通的事情吗?

他们期望二维数组,因为他们使用“行”和“列”来设置值的位置。例如,如果 array[2, 3] = 5,则当 x 为 2 且 y 为 3 时,热图将使用值 5。

那么,让我们尝试将您当前的数据转换成一个数组:

>>> array = np.empty((len(set(X)), len(set(Y))))
>>> for x, y, z in zip(X, Y, Z):
        array[x-1, y-1] = z

如果 XYnp.array,你也可以这样做 (SO answer):

>>> array = np.empty((X.shape[0], Y.shape[0]))
>>> array[np.array(X) - 1, np.array(Y) - 1] = Z

现在只需按照您的喜好绘制数组即可:

>>> plt.imshow(array, cmap="hot", interpolation="nearest")
>>> plt.show()