Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

How to add labels and titles to a plot in matplotlib

Onyejiaku Theophilus Chidalu

Overview

Plots in MatplotlibA comprehensive library for creating static, animated, and interactive visualizations in Python. represent the visualization of the given data. These plots require labels (on x and y-axis) and titles. Every plot has an x and y-axis. These axes represent the values of the plotted data.

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 plt
import numpy as np

x = np.array([1, 5])
y = np.array([10, 20])

plt.plot(x, y)

# using the xlabel and ylabel functions
plt.xlabel("x axis")
plt.ylabel("y axis")
plt.show()
Python: Plot and label the axes
Output of the code

Explanation

  • Line 1: We import the pyplot module from the matplot library.
  • Line 2: We import the numpy module.
  • 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 use the pyplot.plot() method to plot y against x (that is, x on the x-axis and y on 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 plt
import numpy as np

x= np.array([1, 5])
y = np.array([10, 20])

plt.plot(x, y)

# usig the title() method
plt.title('Y against X')
# using the xlabel() and ylabel() methods
plt.xlabel("x axis")
plt.ylabel("y axis")
plt.show()
Python: Title the plot with labelled axes
Output of the code

RELATED TAGS

python
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring