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 pltimport numpy as npx = np.array([1, 5])y = np.array([10, 20])# creating the font propertiesfont1 = {'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 labelsplt.title('Y against X', fontdict = font3 )plt.xlabel("x axis", fontdict = font1)plt.ylabel("y axis", fontdict = font2)plt.plot(x, y)plt.show()
Explanation
- Line 1: We imported the
pyplotmodule from thematplot library. - Line 2: We imported the
numpymodule. - Line 3: We created an array variable
xusing thenumpy.array()method. - Line 4: We created another array variable
yusing thenumpy.array()method. - Line 6-8: We created the font properties of our
fontdict. We passed key value items to its parameters such asfamily,color,and size. - Line 10: Using the
pyplot.title()method, we gave a title to the plot and also passed the value of ourfontdictparameter asfont3. - Line 11: Using the
pyplot.xlabel()method, we gave a label to the x-axis of our plot and also passed the value of ourfontdictparameter asfont1. - Line 12: Using the
pyplot.ylabel()method, we gave a label to the y-axis of our plot and also passed the value of ourfontdictparameter asfont2. - Line 13: Using the
pyplot.plot()method, we plotted theyagainstx(i.e.,xon the x-axis andyon the y-axis. - Line 14: Using the
pyplot.show()method, we asked Python to show us our plot.