How to Set the Figure Title and Axes Labels Font Size in Matplotlib

How do I set the figure title and axes labels font size?

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.

How to change the font size on a matplotlib plot

From the matplotlib documentation,

font = {'family' : 'normal',
'weight' : 'bold',
'size' : 22}

matplotlib.rc('font', **font)

This sets the font of all items to the font specified by the kwargs object, font.

Alternatively, you could also use the rcParams update method as suggested in this answer:

matplotlib.rcParams.update({'font.size': 22})

or

import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 22})

You can find a full list of available properties on the Customizing matplotlib page.

Concise way to set axis label font size in matplotlib

You could change the label for each "axis" instance of the "axes". The text instance returned by "get_label" provides methods to modify the fonts size, but also other properties of the label:

from matplotlib import pylab as plt
import numpy

fig = plt.figure()
ax = fig.add_subplot(111)
ax.grid()

# set labels and font size
ax.set_xlabel('X axis', fontsize = 12)
ax.set_ylabel('Y axis', fontsize = 12)

ax.plot(numpy.random.random(100))

# change font size for x axis
ax.xaxis.get_label().set_fontsize(20)

plt.show()

Matplotlib make tick labels font size smaller

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

Sample Image

How can I add secondary labels with different font sizes to axes in Matplotlib?

The general approach would be to use ax.annotate() but for the x-axis, we can simply use the subplot title:

import matplotlib.pyplot as plt
fig, ax = plt.subplots(3,3,sharex=True,sharey=True,
constrained_layout=False, figsize=(10, 6))

x_titles = list("DEF")
y_titles = list("ABC")
for curr_title, curr_ax in zip(x_titles, ax[0, :]):
curr_ax.set_title(curr_title, fontsize=15)
for curr_title, curr_ax in zip(y_titles, ax[:, 0]):
#the xy coordinates are in % axes from the lower left corner (0,0) to the upper right corner (1,1)
#the xytext coordinates are offsets in pixel to prevent
#that the text moves in relation to the axis when resizing the window
curr_ax.annotate(curr_title, xy=(0, 0.5), xycoords="axes fraction",
xytext=(-80, 0), textcoords='offset pixels',
fontsize=15, rotation="vertical")
plt.show()

Sample output:
Sample Image

How to increase plt.title font size?

import matplotlib.pyplot as plt
plt.figtext(.5,.9,'Temperature', fontsize=100, ha='center')
plt.figtext(.5,.8,'Humidity',fontsize=30,ha='center')
plt.show()

Probably you want this. You can easily tweak the fontsize of both and adjust there placing by changing the first two figtext positional parameters.
ha is for horizontal alignment

Alternatively,

import matplotlib.pyplot as plt

fig = plt.figure() # Creates a new figure
fig.suptitle('Temperature', fontsize=50) # Add the text/suptitle to figure

ax = fig.add_subplot(111) # add a subplot to the new figure, 111 means "1x1 grid, first subplot"
fig.subplots_adjust(top=0.80) # adjust the placing of subplot, adjust top, bottom, left and right spacing
ax.set_title('Humidity',fontsize= 30) # title of plot

ax.set_xlabel('xlabel',fontsize = 20) #xlabel
ax.set_ylabel('ylabel', fontsize = 20)#ylabel

x = [0,1,2,5,6,7,4,4,7,8]
y = [2,4,6,4,6,7,5,4,5,7]

ax.plot(x,y,'-o') #plotting the data with marker '-o'
ax.axis([0, 10, 0, 10]) #specifying plot axes lengths
plt.show()

Output of alternative code:

Sample Image

PS: if this code give error like ImportError: libtk8.6.so: cannot open shared object file esp. in Arch like systems. In that case, install tk using sudo pacman -S tk or Follow this link

Adjust font size of x-axis and y-axis labels in Seaborn Matplotlib PyQT5

sns.barplot(x='Year', y='Buyer Count', data=df) returns a matplotlib Axes, while sns.barplot(x='Year', y='Buyer Count', data=df).set(title="Buyers".format(year)) returns a list as the error told.

p = sns.barplot(x='Year', y='Buyer Count', data=df)
p.set(title="Buyers".format(year))
p.set_xlabel("X-Axis", fontsize = 12)
p.set_ylabel("Y-Axis", fontsize = 12)

Don't call .set method directly, and refactor the code as above. This should not give any errors.

How to change the size of the axis, ticks and labels for a plot in matplotlib

You can change the font size globally:

plt.rcParams['font.size'] = 12

Or you can change it for individual components:

plt.rc('axes', titlesize=12)

plt.rc('axes', labelsize=12)

plt.rc('xtick', labelsize=12)

plt.rc('ytick', labelsize=12)

How to set font size of Matplotlib axis Legend?

This is definitely an old question, but was frustrating me too and none of the other answers changed the legend title fontsize at all, but instead just changed the rest of the text. So after banging my head against the matplotlib documentation for awhile I came up with this.

legend = ax1.legend(loc=0, ncol=1, bbox_to_anchor=(0, 0, 1, 1),
prop = fontP,fancybox=True,shadow=False,title='LEGEND')

plt.setp(legend.get_title(),fontsize='xx-small')

As of Matplotlib 3.0.3, you can also set it globally with

plt.rcParams['legend.title_fontsize'] = 'xx-small'


Related Topics



Leave a reply



Submit