881

I am creating a figure in Matplotlib like this:

from matplotlib import pyplot as plt

fig = plt.figure()
plt.plot(data)
fig.suptitle('test title')
plt.xlabel('xlabel')
plt.ylabel('ylabel')
fig.savefig('test.jpg')

I want to specify font sizes for the figure title and the axis labels. I need all three to be different font sizes, so setting a global font size (mpl.rcParams['font.size']=x) is not what I want. How do I set font sizes for the figure title and the axis labels individually?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
vasek1
  • 13,541
  • 11
  • 32
  • 36

12 Answers12

1211

Functions dealing with text like label, title, etc. accept parameters same as matplotlib.text.Text. For the font size you can use size/fontsize:

from matplotlib import pyplot as plt    

fig = plt.figure()
plt.plot(data)
fig.suptitle('test title', fontsize=20)
plt.xlabel('xlabel', fontsize=18)
plt.ylabel('ylabel', fontsize=16)
fig.savefig('test.jpg')

For globally setting title and label sizes, mpl.rcParams contains axes.titlesize and axes.labelsize. (From the page):

axes.titlesize      : large   # fontsize of the axes title
axes.labelsize      : medium  # fontsize of the x any y labels

(As far as I can see, there is no way to set x and y label sizes separately.)

And I see that axes.titlesize does not affect suptitle. I guess, you need to set that manually.

Neuron
  • 5,141
  • 5
  • 38
  • 59
Avaris
  • 35,883
  • 7
  • 81
  • 72
  • 1
    thanks! is there a way to set that globally but explicitly for (suptitle, xlabel, ylabel)? I am making a lot of charts and just want to specify it once... – vasek1 Sep 16 '12 at 06:12
  • 1
    @vasek1: I thought you didn't want global setting :). For that you need `mpl.rcParams`. I've edited my answer. – Avaris Sep 16 '12 at 06:23
  • 35
    To anyone else like myself looking for the solution to change the titlesize: `plt.rcParams.update({'axes.titlesize': 'small'})` – tommy.carstensen Jun 05 '15 at 13:17
  • 1
    From the `rcParams` link, use `figure.titlesize` in addition to `axes.titlesize`. – Mad Physicist Dec 15 '15 at 19:05
  • @MadPhysicist `u'figure.titlesize is not a valid rc parameter.See rcParams.keys() for a list of valid parameters.'` ... Don't think it works although it is listed strangely enough – Alexander McFarlane May 29 '16 at 22:08
  • 1
    @AlexanderMcFarlane. I ran `python -c 'import matplotlib as mpl; print(mpl.__version__); print("figure.titlesize" in mpl.rcParams.keys())'`. Result is `1.5.1`, `True`. 1) What version of matplotlib are you using? What version of Python? 2) Could it be a bug where for some reason it accepts `str` but not `unicode` in Py2? – Mad Physicist May 30 '16 at 01:18
  • `python: 2.7.11` and `matplotlib: 1.4.3` ... I hate these sorts of bugs they're so pedantic to figure out especially when we have lots of interesting physics to plot! I will just leave it here as a warning in case someone thinks they've done it wrong – Alexander McFarlane May 30 '16 at 01:22
  • Thanks. Is there a way to globally set explicit numeric sizes for the title and the axis-labels instead of always doing `ax.set_title('some title', fontsize=15)`, `ax.set_xlabel('some xlabel', fontsize=12)`? It seems like `rcParams` only accepts strings. – timgeb Jan 20 '19 at 15:56
  • it seems this approach is no longer recommended by the documentation? Could the obj oriented approach be added too? – baxx Apr 12 '20 at 17:36
  • For reasons unknown, when I used this solution "horizontalalignment='center'" did not work for my title. I ended up using "ax.set_title()" as a final solution. – Tanjil Oct 11 '21 at 10:16
151

You can also do this globally via a rcParams dictionary:

import matplotlib.pylab as pylab
params = {'legend.fontsize': 'x-large',
          'figure.figsize': (15, 5),
         'axes.labelsize': 'x-large',
         'axes.titlesize':'x-large',
         'xtick.labelsize':'x-large',
         'ytick.labelsize':'x-large'}
pylab.rcParams.update(params)
tsando
  • 4,557
  • 2
  • 33
  • 35
  • 10
    What are other sizes besides `'x-large'`? – Martin Thoma Oct 11 '17 at 07:00
  • 33
    ‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’. See https://matplotlib.org/api/font_manager_api.html#matplotlib.font_manager.FontProperties.set_size – tsando Oct 11 '17 at 08:37
  • 2
    Use `pylab.rcParams.keys()` to see the full list of parameters. – Nirmal Oct 26 '18 at 05:34
  • Thanks. Is there a way to globally set explicit numeric sizes for the title and the axis-labels instead of always doing `ax.set_title('some title', fontsize=15)`, `ax.set_xlabel('some xlabel', fontsize=12)`? It seems like `rcParams` only accepts strings. – timgeb Jan 20 '19 at 15:57
  • 10
    You can also use numbers... `'axes.labelsize': 32,` – mimoralea Jun 12 '19 at 21:38
  • In addition to `axes.titlesize`, you have this guy `{'figure.titlesize':'medium'}`, who can be reached at (say) `plt.suptitle("SUP", y=0.95)`, where the `y` parameter can be useful. – PatrickT Jan 16 '22 at 06:57
135

If you're more used to using ax objects to do your plotting, you might find the ax.xaxis.label.set_size() easier to remember, or at least easier to find using tab in an ipython terminal. It seems to need a redraw operation after to see the effect. For example:

import matplotlib.pyplot as plt

# set up a plot with dummy data
fig, ax = plt.subplots()
x = [0, 1, 2]
y = [0, 3, 9]
ax.plot(x,y)

# title and labels, setting initial sizes
fig.suptitle('test title', fontsize=12)
ax.set_xlabel('xlabel', fontsize=10)
ax.set_ylabel('ylabel', fontsize='medium')   # relative to plt.rcParams['font.size']

# setting label sizes after creation
ax.xaxis.label.set_size(20)
plt.draw()

I don't know of a similar way to set the suptitle size after it's created.

SpinUp __ A Davis
  • 5,016
  • 1
  • 30
  • 25
  • 2
    `fig.suptitle('test title', fontsize = 20)` seems to work. `ax.set_xlabel('xlabel', fontsize = 20)' also works, in which case we can do away with `ax.xaxis.label.set_size(20)`. – T_T Jun 14 '18 at 04:03
  • 1
    @T_T That's true, and these forms are similar to Avaris' answer above. I'll add them for completeness. I still find a use for `ax.xaxis.label.set_size()` when I'm working interactively with an _ipython_ plot and I want to do a quick visual assessment of a variety of font sizes. – SpinUp __ A Davis Jun 15 '18 at 18:12
  • Do you know if there's any (hidden) difference between using ax objects and figure objects, or are both perfectly equivalent? Why are there different interfaces for some of the features? (plt.xlabel() vs. ax.set_xlabel()) – normanius Nov 14 '18 at 14:33
  • 1
    @normanius, if you mean ax and fig in the above example, they are quite different objects -- fig is the overall figure, which may contain several axes. So fig and ax have different properties. In terms of the difference between the pyplot type calls and object calls (e.g. `plt.xlabel()` vs. `ax.set_xlabel()` as you say), they are equivalent, with the caveat that the `plt.*` functions work on the _current_ axis/figure. So it you set up a figure with multiple axes, you'll probably want to use explicit calls like `ax1.set_xlabel()` to avoid confusion. – SpinUp __ A Davis Nov 14 '18 at 21:48
55

To only modify the title's font (and not the font of the axis) I used this:

import matplotlib.pyplot as plt
fig = plt.Figure()
ax = fig.add_subplot(111)
ax.set_title('My Title', fontdict={'fontsize': 8, 'fontweight': 'medium'})

The fontdict accepts all kwargs from matplotlib.text.Text.

Elazar
  • 20,415
  • 4
  • 46
  • 67
tammoj
  • 908
  • 10
  • 14
  • I'm running Python 3.8.5 and I don't need to use ```fontdict```. It does work, but you can also use: ```ax.set_title("My Title", fontsize=18, fontwieght="medium")```. This also works on ```ax2.set_xticklabels``` etc. – B McMinn Jan 05 '22 at 19:24
45

Per the official guide, use of pylab is no longer recommended. matplotlib.pyplot should be used directly instead.

Globally setting font sizes via rcParams should be done with

import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 16
plt.rcParams['axes.titlesize'] = 16

# or

params = {'axes.labelsize': 16,
          'axes.titlesize': 16}
plt.rcParams.update(params)

# or

import matplotlib as mpl
mpl.rc('axes', labelsize=16, titlesize=16)

# or 

axes = {'labelsize': 16,
        'titlesize': 16}
mpl.rc('axes', **axes)

The defaults can be restored using

plt.rcParams.update(plt.rcParamsDefault)

You can also do this by creating a style sheet in the stylelib directory under the matplotlib configuration directory (you can get your configuration directory from matplotlib.get_configdir()). The style sheet format is

axes.labelsize: 16
axes.titlesize: 16

If you have a style sheet at /path/to/mpl_configdir/stylelib/mystyle.mplstyle then you can use it via

plt.style.use('mystyle')

# or, for a single section

with plt.style.context('mystyle'):
    # ...

You can also create (or modify) a matplotlibrc file which shares the format

axes.labelsize = 16
axes.titlesize = 16

Depending on which matplotlibrc file you modify these changes will be used for only the current working directory, for all working directories which do not have a matplotlibrc file, or for all working directories which do not have a matplotlibrc file and where no other matplotlibrc file has been specified. See this section of the customizing matplotlib page for more details.

A complete list of the rcParams keys can be retrieved via plt.rcParams.keys(), but for adjusting font sizes you have (italics quoted from here)

  • axes.labelsize - Fontsize of the x and y labels
  • axes.titlesize - Fontsize of the axes title
  • figure.titlesize - Size of the figure title (Figure.suptitle())
  • xtick.labelsize - Fontsize of the tick labels
  • ytick.labelsize - Fontsize of the tick labels
  • legend.fontsize - Fontsize for legends (plt.legend(), fig.legend())
  • legend.title_fontsize - Fontsize for legend titles, None sets to the same as the default axes. See this answer for usage example.

all of which accept string sizes {'xx-small', 'x-small', 'smaller', 'small', 'medium', 'large', 'larger', 'x-large', 'xxlarge'} or a float in pt. The string sizes are defined relative to the default font size which is specified by

  • font.size - the default font size for text, given in pts. 10 pt is the standard value

Additionally, the weight can be specified (though only for the default it appears) by

  • font.weight - The default weight of the font used by text.Text. Accepts {100, 200, 300, 400, 500, 600, 700, 800, 900} or 'normal' (400), 'bold' (700), 'lighter', and 'bolder' (relative with respect to current weight).
William Miller
  • 9,839
  • 3
  • 25
  • 46
22

If you aren't explicitly creating figure and axis objects you can set the title fontsize when you create the title with the fontdict argument.

You can set and the x and y label fontsizes separately when you create the x and y labels with the fontsize argument.

For example:

plt.title('Car Prices are Increasing', fontdict={'fontsize':20})
plt.xlabel('Year', fontsize=18)
plt.ylabel('Price', fontsize=16)

Works with seaborn and pandas plotting (when Matplotlib is the backend), too!

jeffhale
  • 3,759
  • 7
  • 40
  • 56
15

Others have provided answers for how to change the title size, but as for the axes tick label size, you can also use the set_tick_params method.

E.g., to make the x-axis tick label size small:

ax.xaxis.set_tick_params(labelsize='small')

or, to make the y-axis tick label large:

ax.yaxis.set_tick_params(labelsize='large')

You can also enter the labelsize as a float, or any of the following string options: 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', or 'xx-large'.

etotheipi
  • 771
  • 9
  • 12
3

An alternative solution to changing the font size is to change the padding. When Python saves your PNG, you can change the layout using the dialogue box that opens. The spacing between the axes, padding if you like can be altered at this stage.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Naz
  • 395
  • 1
  • 4
  • 12
3

Place right_ax before set_ylabel()

ax.right_ax.set_ylabel('AB scale')

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
0

All of the "labeling" calls such as suptitle(), set_xlabel()/plt.xlabel, set_title etc. return a matplotlib.text.Text instance which define a set_size() method to adjust the fontsize. The ways to access these instances vary depending on what is wanted; suptitle can be accessed via fig._suptitle, while xlabel can be accessed via ax.xaxis.label.

from matplotlib import pyplot as plt

fig, ax = plt.subplots()
ax.plot(range(2))
ax.set_title('Subplot title')   # Text(0.5, 1.0, 'Subplot title')
fig.suptitle('Figure title')    # Text(0.5, 0.98, 'Figure title')
ax.set_xlabel('xlabel')         # Text(0.5, 0, 'xlabel')
ax.set_ylabel('ylabel')         # Text(0, 0.5, 'ylabel')

fig._suptitle.set_size(25)      # change figure title size
fig.subplots_adjust(top=0.8)    # make space between subplots and figure

ax.xaxis.label.set_size(15)     # change xlabel size
ax.yaxis.label.set_size(15)     # change ylabel size
ax.title.set_size(15)           # change subplot title size

figure

cottontail
  • 10,268
  • 18
  • 50
  • 51
-4

libraries

import numpy as np

import matplotlib.pyplot as plt

create dataset

height = [3, 12, 5, 18, 45]

bars = ('A', 'B', 'C', 'D', 'E')

x_pos = np.arange(len(bars))

Create bars and choose color

plt.bar(x_pos, height, color = (0.5,0.1,0.5,0.6))

Add title and axis names

plt.title('My title')

plt.xlabel('categories')

plt.ylabel('values')

Create names on the x axis

plt.xticks(x_pos, bars)

Show plot

plt.show()

Tejas PV
  • 7
  • 2
  • 1
    Welcome Tejas! Please consider formatting your answer to make it easier to read. Formatting some parts in [code](https://stackoverflow.com/editing-help#code) would be a good start. – Ali Momen Sani Aug 04 '21 at 19:16
-6

7 (best solution)

 from numpy import*
 import matplotlib.pyplot as plt
 X = linspace(-pi, pi, 1000)

class Crtaj:

    def nacrtaj(self,x,y):
         self.x=x
         self.y=y
         return plt.plot (x,y,"om")

def oznaci(self):
    return plt.xlabel("x-os"), plt.ylabel("y-os"), plt.grid(b=True)

6 (slightly worse solution)

from numpy import*
M = array([[3,2,3],[1,2,6]])
class AriSred(object):
    def __init__(self,m):
    self.m=m
    
def srednja(self):
    redovi = len(M)
    stupci = len (M[0])
    lista=[]
    a=0
    suma=0
    while a<stupci:
        for i in range (0,redovi):
            suma=suma+ M[i,a]
        lista.append(suma)
        a=a+1
        suma=0
    b=array(lista) 
    b=b/redovi
    return b



OBJ = AriSred(M)
sr = OBJ.srednja()
Community
  • 1
  • 1
  • 5
    While this code may provide a solution to OP's problem, it is highly recommended that you provide additional context regarding why and/or how this code answers the question. Code only answers typically become useless in the long-run because future viewers experiencing similar problems cannot understand the reasoning behind the solution. – E. Zeytinci Jan 14 '20 at 07:45
  • better use english. – Nikolai Ehrhardt Apr 09 '22 at 17:18