首页 > 解决方案 > 使用 matplotlib,如何将 xlabels 移动到顶部并在网格线之间居中所有标签?

问题描述

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

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

标签: pythonmatplotliblabel

解决方案


如果我理解正确,请使用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()

输出:

在此处输入图像描述


推荐阅读