0

我正在尝试使用 matplotlib 在 python 中创建热图。我将在 Latex 中使用生成的图形,这就是我将其保存为 .pgf 格式的原因。我有不同长度的 y 轴标签,它们没有正确对齐:

.pgf 中的热图

我的代码:

matplotlib.use("pgf")
matplotlib.rcParams.update({
    "pgf.texsystem": "pdflatex",
    'font.family': 'serif',
    'text.usetex': True,
    'pgf.rcfonts': False,
    'font.size': 6,
})

col_names = ["Bison", "Fox", "Black-Tailed Jackrabbit",
             "Beaver", "African Elephant"]
corr_matrix = pd.DataFrame(np.random.randint(
    0, 100, size=(5, 5)), columns=col_names)

fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(corr_matrix, cmap='Blues', vmin=0, vmax=100)
fig.colorbar(cax)
ticks = np.arange(0, len(corr_matrix.columns), 1)
ax.set_xticks(ticks)
plt.xticks(rotation=90)
ax.set_yticks(ticks)
ax.set_xticklabels(corr_matrix.columns)
ax.set_yticklabels(corr_matrix.columns)
for (i, j), z in np.ndenumerate(corr_matrix):
    ax.text(j, i, z, ha='center', va='center')

plt.savefig('heatmap.pgf', bbox_inches='tight')

当我直接用 plt.show() 显示图形时,对齐是正确的:

带有 plt.show() 的热图

4

1 回答 1

1

我找到了一个解决方案:

for lab in ax.yaxis.get_ticklabels():
    lab.set_verticalalignment("center")

(我不知道为什么这完全有效,我从那里得到了这个想法https://github.com/matplotlib/matplotlib/issues/4115

于 2020-12-11T00:31:22.890 回答