yticks have unexpectedly variable font size

Viewed 67

I am modifying the yticks font size of a figure but not all yticks are of the same font size. The last two yticks 0.8 and 0.6 are greater than the others.

def mm_to_inch(value):
    return value/25.4

import matplotlib
matplotlib.use('Agg')
matplotlib.rcParams['font.sans-serif'] = "Arial"
matplotlib.rcParams['font.family'] = "sans-serif"
matplotlib.rcParams['figure.dpi'] = 300
import pandas as pd
import matplotlib.pyplot as plt

size = 112
fig, ax1 = plt.subplots(figsize=(mm_to_inch(size), mm_to_inch(size/2)))

df = pd.read_csv('testing_errors_prob.csv')
df = df.drop(['precision', 'recall', 'TP', 'FP', 'TN', 'FN'], axis=1)
df = df.sort_values(by=['accuracy'], ascending=False)
df = df.replace({'Gaussian Nb': 'Gaussian\nNb', 'Extra Trees': 'Extra\nTrees', 'Random Forest': 'Random\nForest',
                     'Decision Tree': 'Decision\nTree', 'Gradient Boost': 'Gradient\nBoost', 'Linear SVC': 'Linear\nSVC',
                     'Ada Boost': 'Ada\nBoost', 'Bernouli Nb': 'Bernouli\nNb'})
df.plot.bar(x='model', ax=ax1, color=['#093145', '#107896', '#829356'], width=0.8)
plt.tight_layout()

# plt.xticks(rotation=45, ha="right", fontsize=6)
# plt.yticks(fontsize=6)
plt.xticks(rotation=45, ha="right", fontsize=6)
plt.yticks(fontsize=6)
plt.legend(["Accuracy", "F1", "AUC ROC"], fontsize="xx-large", prop={'size': 5})

plt.subplots_adjust(left=0.07, right=0.9, top=0.9, bottom=0.2)
plt.xlabel('')

plt.savefig('results_updateddd_{}.png'.format(size))
plt.savefig('results_updateddd_{}.pdf'.format(size))
plt.close()

The figure looks like this: enter image description here

2 Answers

I am still not sure why, but the bug was from plt.yticks(fontsize=6). I removed it and replaced it with

ax1.tick_params(axis='both', which='major', labelsize=6)

The main issue is that subplots_adjust causes new yticks to appear when it alters the subplot layout:

  • yticks(fontsize=6) only targets existing ticks, so it will not affect any future ticks that show up (e.g., new ticks that appear after subplots_adjust)
  • tick_params(labelsize=6) sets the tick size for the whole Axes, so even when new ticks show up, they automatically inherit this tick size just by being part of the Axes

So if you want to use the yticks(fontsize=6) method, make sure to call it last:

...
plt.subplots_adjust(left=0.07, right=0.9, top=0.9, bottom=0.2)
plt.yticks(fontsize=6)
...
fontsize -> subplots_adjust subplots_adjust -> fontsize
fontsize first subplots_adjust first
Related