[英]matplotlib python: y-axis labels not aligned in PGF format
我正在嘗試使用 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() 直接顯示圖形時,alignment 是正確的:
我找到了一個解決方案:
for lab in ax.yaxis.get_ticklabels():
lab.set_verticalalignment("center")
(我不知道為什么這完全有效,我從那里得到了想法https://github.com/matplotlib/matplotlib/issues/4115 )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.