Matplotlib的matshow与网格不对齐

2024-09-30 16:26:30 发布

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

我有一个6x6矩阵代表一个网格。以下网格(3)的较小部分表示为3xi:

In [65]:

arr = np.zeros((6,6))
arr[0:3, 0:3] = 1
arr
Out[65]:
array([[ 1.,  1.,  1.,  0.,  0.,  0.],
       [ 1.,  1.,  1.,  0.,  0.,  0.],
       [ 1.,  1.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.]])

我希望绘制这个图,但是matplotlib没有对齐,如下所示。红方应该在水平轴和垂直轴上覆盖0到3的区域。在

^{pr2}$

enter image description here

我怎么解决这个问题?谢谢你


Tags: in网格区域matplotlibnpzeros水平绘制
2条回答

可以对标签使用主刻度,对网格使用次要刻度。在

考虑:

import matplotlib.pyplot as plt
import numpy as np

arr = np.zeros((6,6))
arr[0:3, 0:3] = 1

plt.matshow(arr)

# This is very hack-ish
plt.gca().set_xticks([x - 0.5 for x in plt.gca().get_xticks()][1:], minor='true')
plt.gca().set_yticks([y - 0.5 for y in plt.gca().get_yticks()][1:], minor='true')
plt.grid(which='minor')

plt.show()

这表明:

Output

诀窍就在这两行:

^{pr2}$

如果您愿意,您可以使用:

matshow(arr, extent=[0, 6, 0, 6])

然而,标准行为与预期一致:以(0,0)为中心的像素具有元素(0,0)的值。在

相关问题 更多 >