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

标签 python matplotlib plot

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

x = [2, 3, 4, 5]
y = [1, 1, 1, 1]

我正在使用以下代码,例如,在关于 how to generate 2D histograms in 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')

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

我期待的是:

enter image description here

但是我得到了

Plot showing data plotted in an unexpected, wrong way

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

这是怎么回事?

最佳答案

plt.imshow 输入数组索引的图像空间约定。即右上角的 (0, 0) 和向下的 y 轴。

为避免这种情况,您必须使用可选参数 origin = 'lower'(以更正原点)调用 plt.imshow 并将数据转置为 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')

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

关于python - 为什么我用 matplotlib.imshow 绘制的 matplotlib 2D 直方图/热图与我的轴不匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40293188/

相关文章:

python - 为什么 cross_val_predict 不适合测量泛化误差?

python - 如何正确运行 setup.py 文件?

python - 如何在 Mac 上的 Redis 上运行 Python 应用程序?

python - 使用 for 循环绘制数据框列

python - 如何在 matplotlib 或 seaborn 中使用彩色形状作为 yticks?

python-3.x - Plot_confusioin_matrix 图不显示整数值,而是显示一些指数值

matlab - 如何在分组条形图的顶部绘制一条线?

r - ggplot2/gis 在多边形区域内绘图

r - 在 r、ggplot2、lattice 或latticeExtra 中创建更连续的调色板

python - Pandas 与正则表达式 "."点元字符不一致?