使用 matplotlib,如何将 xlabels 移动到顶部并使所有标签在网格线之间居中?

Using matplotlib, how do I move the xlabels to the top and center all labels between gridlines?

我正在尝试创建一个 10x10 网格,其中每个单元格都是黑色或白色。我主要按照我想要的方式工作,但我想将 x 标签移动到网格的顶部,并且我希望所有标签都在不与它们对齐的网格线之间居中。我该怎么做?

import numpy as np
import matplotlib.pyplot as plt

# data = random.random((10, 10))
face = [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 0, 0, 1, 1, 1, 0, 0, 1, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 1, 1, 1, 0, 1, 1, 1, 1, 1],
        [1, 1, 1, 1, 0, 0, 1, 1, 1, 1],
        [1, 0, 1, 1, 1, 1, 1, 1, 0, 1],
        [1, 1, 0, 1, 1, 1, 1, 0, 1, 1],
        [1, 1, 1, 0, 0, 0, 0, 1, 1, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]

img = plt.imshow(face, interpolation='nearest')

img.set_cmap('hot')
plt.axis('on')
plt.xticks(np.arange(0, 11, 1) - 0.5, np.arange(0, 11, 1))
plt.yticks(np.arange(0, 11, 1) - 0.5, np.arange(0, 11, 1))
plt.grid(True, linestyle='dotted', linewidth=1, color='k')
plt.plot()
plt.savefig("test.png", bbox_inches='tight')
plt.show()

如果我理解正确,请使用 matshow 而不是 imshow。另外,使用 minor 个标记进行标记:

fig, ax = plt.subplots()
img = ax.matshow(face, interpolation='nearest', cmap='hot')

ax.set_xticks(np.arange(10), minor=True)
ax.set_xticklabels(np.arange(10), minor=True)

ax.set_yticks(np.arange(10), minor=True)
ax.set_yticklabels(np.arange(10), minor=True)

plt.xticks(np.arange(11)-0.5,[])
plt.yticks(np.arange(11)-0.5,[])

plt.grid(True, linestyle='dotted', linewidth=1, color='k')
plt.plot()
# plt.savefig("test.png", bbox_inches='tight')
plt.show()

输出: