matplotlib python:yaxis标签未以PGF格式对齐

2024-06-01 07:28:11 发布

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

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

heatmap in .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()直接显示图形时,对齐是正确的:

heatmap with plt.show()


Tags: columnsin图形matplotlibnpfigpltax
1条回答
网友
1楼 · 发布于 2024-06-01 07:28:11

我找到了一个解决方案:

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

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

相关问题 更多 >