How to add labels and titles to a plot in matplotlib
Overview
Plots in
How to add labels to a plot
In matplotlib, we use the pyplot.xlabel() and pyplot.ylabel() functions to label the x and y-axis of the plot, respectively.
Example
Let’s create a plot and label its x and y-axes as follows:
import matplotlib.pyplot as pltimport numpy as npx = np.array([1, 5])y = np.array([10, 20])plt.plot(x, y)# using the xlabel and ylabel functionsplt.xlabel("x axis")plt.ylabel("y axis")plt.show()
Explanation
- Line 1: We import the
pyplotmodule from thematplotlibrary. - Line 2: We import the
numpymodule. - Line 4: We use the
numpy.array()method to create an array variablex. - Line 5: We use the
numpy.array()method to create another array variable,y. - Line 7: We use the
pyplot.plot()method to plotyagainstx(that is,xon the x-axis andyon the y-axis). - Line 10: We use the
pyplot.xlabel()method to label the x-axis of our plot. - Line 11: We use the
pyplot.ylabel()method to label the y-axis of our plot. - Line 12: We use the
pyplot.show()method to ask Python to show us our plot.
How to add a title to a plot
In Matplotlib, we use the pyplot.title() method to give a title to a plot.
Example
Let’s create a plot and give it a title, as follows:
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()