[python] Matplotlib make tick labels font size smaller

In a matplotlib figure, how can I make the font size for the tick labels using ax1.set_xticklabels() smaller?

Further, how can one rotate it from horizontal to vertical?

This question is related to python matplotlib

The answer is


Alternatively, you can just do:

import matplotlib as mpl
label_size = 8
mpl.rcParams['xtick.labelsize'] = label_size 

You can also change label display parameters like fontsize with a line like this:

zed = [tick.label.set_fontsize(14) for tick in ax.yaxis.get_major_ticks()]

plt.tick_params(axis='both', which='minor', labelsize=12)

The following worked for me:

ax2.xaxis.set_tick_params(labelsize=7)
ax2.yaxis.set_tick_params(labelsize=7)

The advantage of the above is you do not need to provide the array of labels and works with any data on the axes.


There is a simpler way actually. I just found:

import matplotlib.pyplot as plt
# We prepare the plot  
fig, ax = plt.subplots()

# We change the fontsize of minor ticks label 
ax.tick_params(axis='both', which='major', labelsize=10)
ax.tick_params(axis='both', which='minor', labelsize=8)

This only answers to the size of label part of your question though.


For smaller font, I use

ax1.set_xticklabels(xticklabels, fontsize=7)

and it works!


Another alternative

I have two plots side by side and would like to adjust tick labels separately.

The above solutions were close however they were not working out for me. I found my solution from this matplotlib page.

ax.xaxis.set_tick_params(labelsize=20)

This did the trick and was straight to the point. For my use case, it was the plot on the right that needed to be adjusted. For the plot on the left since I was creating new tick labels I was able to adjust the font in the same process as seting the labels.

ie

ax1.set_xticklabels(ax1_x, fontsize=15)
ax1.set_yticklabels(ax1_y, fontsize=15)

thus I used for the right plot,

ax2.xaxis.set_tick_params(labelsize=24)
ax2.yaxis.set_tick_params(labelsize=24)

A minor subtlety... I know... but I hope this helps someone :)

Bonus points if anyone knows how to adjust the font size of the order of magnitude label.

enter image description here


To specify both font size and rotation at the same time, try this:

plt.xticks(fontsize=14, rotation=90)

In current versions of Matplotlib, you can do axis.set_xticklabels(labels, fontsize='small').