421

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?

Ninjakannon
  • 3,551
  • 6
  • 50
  • 70
Open the way
  • 23,973
  • 47
  • 137
  • 193
  • Thanks for asking this question, I'm trying to solve this problem right now. I'm not strongly opinionated here, but looks like voters think the best answer is not the accepted one. What do you think? – Russia Must Remove Putin Jun 18 '17 at 19:25
  • did I properly read that there are at least 5 different ways to change the fontsize in matplotlib? :D – famargar Feb 26 '18 at 13:06

10 Answers10

703

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.

Autiwa
  • 7,172
  • 2
  • 11
  • 10
309

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

plt.xticks(fontsize=14, rotation=90)
scottlittle
  • 15,865
  • 5
  • 45
  • 66
  • 11
    Note that this is used when working with MATLAB-like pyplot interface. In case of object-oriented interface tick_params() method of the axes object or set_tick_params() method of the axis object should be used (see other answers). – wombatonfire Jul 20 '18 at 17:45
157

Please note that newer versions of MPL have a shortcut for this task. An example is shown in the other answer to this question: https://stackoverflow.com/a/11386056/42346

The code below is for illustrative purposes and may not necessarily be optimized.

import matplotlib.pyplot as plt
import numpy as np

def xticklabels_example():
    fig = plt.figure() 

    x = np.arange(20)
    y1 = np.cos(x)
    y2 = (x**2)
    y3 = (x**3)
    yn = (y1,y2,y3)
    COLORS = ('b','g','k')

    for i,y in enumerate(yn):
        ax = fig.add_subplot(len(yn),1,i+1)

        ax.plot(x, y, ls='solid', color=COLORS[i]) 

        if i != len(yn) - 1:
            # all but last 
            ax.set_xticklabels( () )
        else:
            for tick in ax.xaxis.get_major_ticks():
                tick.label.set_fontsize(14) 
                # specify integer or one of preset strings, e.g.
                #tick.label.set_fontsize('x-small') 
                tick.label.set_rotation('vertical')

    fig.suptitle('Matplotlib xticklabels Example')
    plt.show()

if __name__ == '__main__':
    xticklabels_example()

enter image description here

Community
  • 1
  • 1
mechanical_meat
  • 155,494
  • 24
  • 217
  • 209
  • 93
    Just as an aside: Instead of looping through the tick label objects, you can use `plt.setp`. (Also, have a look at `ax.tick_params`) For example, you can just do `plt.setp(ax.get_xticklabels(), rotation='vertical', fontsize=14)`. Also, axes objects have an `ax.is_last_row()` method which can be handy in cases like your example. Instead of `if i != len...`, you can do `if not ax.is_last_row()`. (Why it's a method, I have no clue... Matplotlib hates properties, apparently!) – Joe Kington Jun 18 '11 at 02:11
  • 1
    @Joe: this is my first time hearing about `is_last_row()`, thank you! I've used `plt.setp` in the past, and wasn't necessarily sure it represented a more canonical way of customizing tick labels. You've removed that doubt, thanks. More broadly: your answers, especially in the `matplotlib` tag, frequently leave me in awe. Keep up the great work. – mechanical_meat Jun 18 '11 at 02:51
  • 2
    Thanks!! I appreciate the kind words, especially from you! Canonical is very relative, in this case. `plt.setp` is a "matlab-ism", and an explicit loop is probably much more pythonic. Being a matlab convert, myself, `setp` feels natural, but to each their own. Either one is quite readable, i.m.o. – Joe Kington Jun 18 '11 at 03:36
  • 66
    In new versions I found that you had to use the _labelsize_ parameter: e.g. `ax.tick_params(axis='x', labelsize=8)` – Vladtn Feb 16 '12 at 20:49
  • Should be `get_ticklabels` not `get_major_ticks` – jez Jun 15 '15 at 10:25
68

Alternatively, you can just do:

import matplotlib as mpl
label_size = 8
mpl.rcParams['xtick.labelsize'] = label_size 
user2468932
  • 901
  • 6
  • 6
61

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

Kyle Swanson
  • 1,048
  • 1
  • 10
  • 19
50
plt.tick_params(axis='both', which='minor', labelsize=12)
Georgy
  • 9,972
  • 7
  • 57
  • 66
jingweimo
  • 4,472
  • 8
  • 41
  • 69
23

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

Christoph
  • 5,240
  • 6
  • 35
  • 60
16

For smaller font, I use

ax1.set_xticklabels(xticklabels, fontsize=7)

and it works!

Little Bobby Tables
  • 4,126
  • 4
  • 26
  • 45
Pengyao
  • 748
  • 8
  • 15
15

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()]
ATX_Bigfoot
  • 159
  • 1
  • 3
  • 2
    I think that using list comprehensions that have side effects is not the best practice. I'd suggest using a standard for loop instead. – jjmontes Jul 31 '19 at 17:59
14

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.

Rohit Poudel
  • 1,642
  • 2
  • 18
  • 20
Cryptoman
  • 161
  • 1
  • 3