首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >matplotlib python: Y轴标签未按PGF格式对齐

matplotlib python: Y轴标签未按PGF格式对齐
EN

Stack Overflow用户
提问于 2020-12-11 07:43:55
回答 1查看 66关注 0票数 0

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

heatmap in .pgf

我的代码:

代码语言:javascript
复制
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()

EN

回答 1

Stack Overflow用户

发布于 2020-12-11 08:31:23

我找到了一个解决方案:

代码语言:javascript
复制
for lab in ax.yaxis.get_ticklabels():
    lab.set_verticalalignment("center")

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65243861

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档