How to set font properties for title and labels in Matplotlib

Overview

Plots in Matplotlib are used to represent the visualization of a given data. These plots require the need for labels (x and y-axis) as well as the title of the plot. Every plot has the x and y-axis. These axes represent the values of the data set plotted against the other.

Now, these titles and labels can also be given different font properties to enhance the visuals of the plot.

Adding font properties to a plot

In Matplotlib, we use the fontdict parameter of the pyplot.xlabel() , pyplot.ylabel() and pyplot.title() functions to set font properties for the titles and labels of a plot. The fontdict function on its own takes parameters such as:

  • Family: serif, cursive, sans-serif, fantasy, monospace.
  • Color: blue, green, cyan, white, yellow, etc.
  • Size: Any positive integer value.

Example

Now, let’s create a plot and set the font properties for the titles and labels of the plot.

import matplotlib.pyplot as plt
import numpy as np
x = np.array([1, 5])
y = np.array([10, 20])
# creating the font properties
font1 = {'family':'fantasy','color':'blue','size':20}
font2 = {'family':'serif','color':'darkred','size':15}
font3 = {'family':'cursive','color':'green','size':20}
# passing the fontdict parameter to the title as well as the x and y labels
plt.title('Y against X', fontdict = font3 )
plt.xlabel("x axis", fontdict = font1)
plt.ylabel("y axis", fontdict = font2)
plt.plot(x, y)
plt.show()
Output of the code

Explanation

  • Line 1: We imported the pyplot module from the matplot library.
  • Line 2: We imported the numpy module.
  • Line 3: We created an array variable x using the numpy.array() method.
  • Line 4: We created another array variable y using the numpy.array() method.
  • Line 6-8: We created the font properties of our fontdict. We passed key value items to its parameters such as family, color, and size.
  • Line 10: Using the pyplot.title() method, we gave a title to the plot and also passed the value of our fontdict parameter as font3.
  • Line 11: Using the pyplot.xlabel() method, we gave a label to the x-axis of our plot and also passed the value of our fontdict parameter as font1.
  • Line 12: Using the pyplot.ylabel() method, we gave a label to the y-axis of our plot and also passed the value of our fontdict parameter as font2.
  • Line 13: Using the pyplot.plot() method, we plotted the y against x (i.e., x on the x-axis and y on the y-axis.
  • Line 14: Using the pyplot.show() method, we asked Python to show us our plot.

Free Resources