How to position a title in matplotlib
Overview
In this shot, we will learn how to position the title of a plot in the matplotlib library. Plots in matplotlib are used to represent the visualization of given data and require a title for identification.
How to add a title to a plot
In matplotlib, we use the pyplot.title() method to give a plot a title.
Example
Let’s create a plot and give it a title.
import matplotlib.pyplot as pltimport numpy as npx= np.array([1, 5])y = np.array([10, 20])plt.plot(x, y)# usig the title() methodplt.title('Y against X')# using the xlabel() and ylabel() methodsplt.xlabel("x axis")plt.ylabel("y axis")plt.show()
Explanation
- Line 1: We import the
pyplotmodule from thematplotliblibrary asplt. - Line 2: We import the
numpymodule. - Line 4: We use the
numpy.array()method to create an array variable,x. - Line 5: We use the
numpy.array()method to create another array variable,y. - Line 7: We plot
yagainstx(xon the x-axis andyon the y-axis) with theplt.plot()method. - Line 10: We use the
plt.title()method to give our plot a title. - Line 12: We use the
plt.xlabelmethod to label the x-axis of our plot. - Line 13: We use the
plt.ylabel()method to label the y-axis of our plot. - Line 14: We use the
plt.show()method to display our plot.
How to position the title of a plot
In matplotlib, we use the loc parameter of the plt.title() function to give a specified position to a title. loc takes the following values:
rightleftcenter
The value of loc is center by default.
Example
Let’s position the plot’s title to our desired position.
import matplotlib.pyplot as pltimport numpy as npx= np.array([1, 5])y = np.array([10, 20])plt.plot(x, y)# usig the title() method and insertion the loc parameter with left as its valueplt.title('Y against X', loc='left')# using the xlabel() and ylabel() methodsplt.xlabel("x axis")plt.ylabel("y axis")plt.show()
Explanation
- Line 1: We import the
pyplotmodule from thematplotlib libraryasplt. - Line 2: We import the
numpymodule. - Line 4: We use the
numpy.array()method to create an array variable,x. - Line 5: We use the
numpy.array()method to create another array variable,y. - Line 7: We plot
yagainstx(xon the x-axis andyon the y-axis) with theplt.plot()method. - Line 10: We use the
plt.title()method to give a title to our plot and give thelocparameter to position the title of the plot to theleft. - Line 12: We use the
plt.xlabel()method to label the x-axis of our plot. - Line 13: We use the
plt.ylabel()method to label the y-axis of our plot. - Line 14: We use the
plt.show()method to display our plot.