我正在尝试使用 matplotlib 在 python 中创建热图。我将在 Latex 中使用生成的图形,这就是我将其保存为 .pgf 格式的原因。我有不同长度的 y 轴标签,它们没有正确对齐:
我的代码:
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() 显示图形时,对齐是正确的: