matplotlib python: y-axis labels not aligned in PGF format

256 views Asked by At

I am trying to create a heatmap in python with matplotlib. I will use the generated graphic in latex, which is why i am saving it in .pgf format. I have y-axis labels of varying length, which are not aligned correctly:

heatmap in .pgf

My Code:

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')

When I show the graphic directly with plt.show(), the alignment is correct:

heatmap with plt.show()

1

There are 1 answers

0
Programmer8637485 On

I have found a solution:

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

(I don't know why this works exactly, I got the idea from there https://github.com/matplotlib/matplotlib/issues/4115)