为什么我的matplotlib二维直方图/热图是用matplotlib.imshow与我的斧头不匹配?

2024-06-09 16:10:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图为以下数据创建一个柱状图

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

我正在使用下面的代码,例如,在旧版本中描述了这个关于how to generate 2D histograms in matplotlib问题的答案。在

^{pr2}$

然而,这产生的情节似乎在某种程度上是旋转的。在

我本以为会这样:

enter image description here

但我有

Plot showing data plotted in an unexpected, wrong way

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

怎么回事?在


Tags: to数据答案代码inmatplotlibgeneratehow
1条回答
网友
1楼 · 发布于 2024-06-09 16:10:30

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')

或者更好地使用^{}来完全避免这个问题。在

相关问题 更多 >