【问题标题】:matplotlib python: y-axis labels not aligned in PGF formatmatplotlib python:y轴标签未以PGF格式对齐
【发布时间】:2020-12-10 23:43:54
【问题描述】:

我正在尝试使用 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()

【问题讨论】:

    标签: python matplotlib latex pgf


    【解决方案1】:

    我找到了解决办法:

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

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

    【讨论】:

      猜你喜欢
      • 2015-07-19
      • 1970-01-01
      • 2014-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-24
      • 2017-02-02
      • 1970-01-01
      相关资源
      最近更新 更多