为什么我用 matplotlib.imshow 绘制的 matplotlib 2D 直方图/热图与我的轴不匹配?

Mic*_*rer 3 python plot matplotlib

我正在尝试为以下数据创建直方图

x = [2, 3, 4, 5]
y = [1, 1, 1, 1]
Run Code Online (Sandbox Code Playgroud)

我正在使用以下代码,例如,在关于如何在 matplotlib 中生成二维直方图的这个问题的答案的旧版本中进行了描述。

import matplotlib.pyplot as plt
import numpy as np

bins = np.arange(-0.5, 5.5, 1.0), np.arange(-0.5, 5.5, 1.0)
heatmap, xedges, yedges = np.histogram2d(x, y, bins=bins)
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]

plt.clf()
plt.imshow(heatmap,
           extent=extent,
           interpolation='nearest',
           cmap=plt.get_cmap('viridis'), # use nicer color map
          )
plt.colorbar()

plt.xlabel('x')
plt.ylabel('y')
Run Code Online (Sandbox Code Playgroud)

然而,这产生的情节似乎以某种方式旋转。

我期待这个:

在此处输入图片说明

但我得到了

绘图显示以意外、错误的方式绘制的数据

显然,这与我的输入数据不匹配。此图中突出显示的坐标是(1, 0), (1, 1), (1, 2), (1, 3)

到底是怎么回事?

Mic*_*rer 5

plt.imshow用于对输入数组进行索引的图像空间约定。也就是说,(0, 0)在右上角和向下定向的 y 轴。

为避免这种情况,您必须plt.imshow使用可选参数 origin = 'lower' (以更正原点)调用并传递转置数据heatmap.T以更正轴的翻转。

但这不会让你得到正确的情节。不仅起源在错误的地方,而且索引约定也不同。numpy 数组遵循行/列索引,而图像通常使用列/行索引。因此,此外,您必须转置数据。

所以最后,你的代码应该是这样的:

import matplotlib.pyplot as plt
import numpy as np

bins = np.arange(-0.5, 5.5, 1.0), np.arange(-0.5, 5.5, 1.0)
heatmap, xedges, yedges = np.histogram2d(x, y, bins=bins)
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]

plt.clf()
plt.imshow(heatmap.T,
           origin='lower',
           extent=extent,
           interpolation='nearest',
           cmap=plt.get_cmap('viridis'), # use nicer color map
          )
plt.colorbar()

plt.xlabel('x')
plt.ylabel('y')
Run Code Online (Sandbox Code Playgroud)

或者甚至更好地使用matplotlib.pyplot.hist2d来完全避免这个问题。