Basics of Matplotlib

Greetings! Some links on this site are affiliate links. That means that, if you choose to make a purchase, The Click Reader may earn a small commission at no extra cost to you. We greatly appreciate your support!

In this chapter, we will learn about all the basics of Matplotlib along with visual examples and descriptive code.

By learning about the terminologies, we can start to create our own line plot using Matplotlib. We will also change the different properties of a line plot and explore everything that there is to plotting with Matplotlib.

The terminologies of a Matplotlib plot

The following diagram shows the different terminologies used to describe a Matplotlib plot. Learning these at the beginning will be helpful since most methods used for plotting Matplotlib plots are based on the terminologies.

basics of matplotlib plots
  • Title: The title of a Matplotlib plot is the heading that appears at the top of the figure.
  • Axes: It is the region where data is plotted on a Matplotlib plot.
  • Axis: These are the number-line-like objects. They take care of setting the graph limits and generating the ticks (the marks on the axis) and tick labels (strings labeling the ticks).
  • Grid: It is the dotted line that divides the axes into multiple equal square spaces.
  • Label: It is the notation for axis. For instance, we can define the x-axis label and y-axis label names.
  • Legend: It is the notation for plots in the figure. It is often represented with distinct colors, shapes, and names.
  • Figure: A figure in Matplotlib means the whole window in the user interface. Within this figure, there can be “subplots” that help to arrange plots in a regular grid where we need to specify the number of rows and columns and the number of the plot.

Plotting your first Matplotlib Line Plot

In this section, you will learn how to plot a simple line plot in Matplotlib.

First, import the Matplotlib library in Python using the knowledge gained from the previous chapter.

# Libraries/Modules import conventions
import matplotlib.pyplot as plt  

# For interactive matplotlib sessions, turn on the matplotlib inline mode
%matplotlib inline

Since we need some data to plot, let us define two Python lists representing the points of the line that we are about to plot.

# Dummy Data
X = [1, 2, 3, 4]
Y = [2, 4, 6, 8]

Now, we can plot a line plot using the plot() method and show that plot using the show() method:

# plot() is used for plotting a line plot and show() is used for displaying the plot
plt.plot(X, Y)
plt.show()
basic plotting in matplotlib

Piecing all the code together, this is how you create a line plot in Matplotlib.

# Libraries/Modules import conventions
import matplotlib.pyplot as plt  

# For interactive matplotlib sessions, turn on the matplotlib inline mode
%matplotlib inline

# Dummy Data
X = [1, 2, 3, 4]
Y = [2, 4, 6, 8]

# plot() is used for plotting a line plot and show() is used for displaying the plot
plt.plot(X, Y)
plt.show()

Congratulations, you just made your first plot in Matplotlib! Moving onwards, we will try to make this plot even more informative and interesting by using the various properties mentioned at the beginning of this chapter.

Adding a Title and Axis Labels onto the Matplotlib plot

You can provide a title and axis labels to the plot using the title()xlabel() and ylabel() methods as shown below:

# Libraries/Modules import conventions
import matplotlib.pyplot as plt  

# For interactive matplotlib sessions, turn on the matplotlib inline mode
%matplotlib inline

# Dummy Data
X = [1, 2, 3, 4]
Y = [2, 4, 6, 8]

# plot() is used for plotting a line plot
plt.plot(X, Y)

# Adding title, xlabel and ylabel
plt.title('A Basic Line Plot') #Title of the plot
plt.xlabel('X-axis') #X-Label
plt.ylabel('Y-axis') #Y-Label

# show() is used for displaying the plot
plt.show()
matplotlib line plot with labels

Changing the color and width of the line plot

We can change the color and width of the line plot by defining the ‘color’ and ‘linewidth’ properties as follows:

# Libraries/Modules import conventions
import matplotlib.pyplot as plt  

# For interactive matplotlib sessions, turn on the matplotlib inline mode
%matplotlib inline

# Dummy Data
X = [1, 2, 3, 4]
Y = [2, 4, 6, 8]

# plot() is used for plotting a line plot
plt.plot(X, Y, color = 'green', linewidth = 5)

# Adding title, xlabel and ylabel
plt.title('A Basic Line Plot') #Title of the plot
plt.xlabel('X-axis') #X-Label
plt.ylabel('Y-axis') #Y-Label

# show() is used for displaying the plot
plt.show()
matplotlib line plot with color

Changing the figure size of the line plot

The dimensions (width and height) of the line plot can be changed as following by defining a figure() method before plotting as follows:

# Libraries/Modules import conventions
import matplotlib.pyplot as plt  

# For interactive matplotlib sessions, turn on the matplotlib inline mode
%matplotlib inline

# Dummy Data
X = [1, 2, 3, 4]
Y = [2, 4, 6, 8]

# Defining the figure shape
fig = plt.figure(figsize = (10, 4)) # Width is 10 and height is 4

# plot() is used for plotting a line plot
plt.plot(X, Y, color = 'green', linewidth = 5)

# Adding title, xlabel and ylabel
plt.title('A Basic Line Plot') #Title of the plot
plt.xlabel('X-axis') #X-Label
plt.ylabel('Y-axis') #Y-Label

# show() is used for displaying the plot
plt.show()
matplotlib change figure size

Annotating text and adding an arrow onto the Matplotlib Line Plot

We can annotate text at a particular position of the plot using the annotate() method by specifying the following properties:

  • xy: The point *(x,y)* to annotate.
  • xytext: The position *(x,y)* to place the text at.
  • arrowprops: Properties of the arrow as a dictionary.
# Libraries/Modules import conventions
import matplotlib.pyplot as plt  

# For interactive matplotlib sessions, turn on the matplotlib inline mode
%matplotlib inline

# Dummy Data
X = [1, 2, 3, 4]
Y = [2, 4, 6, 8]

# Defining the figure shape
fig = plt.figure(figsize = (10, 4)) # Width is 10 and height is 4

# plot() is used for plotting a line plot
plt.plot(X, Y, color = 'green', linewidth = 5)

# Adding annotations
plt.annotate('This is a line', xy=(2.5, 5.5), xytext=(1.5, 7),
             arrowprops={'facecolor':'black', 'shrink':0.05},
             )

# Adding title, xlabel and ylabel
plt.title('A Basic Line Plot') #Title of the plot
plt.xlabel('X-axis') #X-Label
plt.ylabel('Y-axis') #Y-Label

# show() is used for displaying the plot
plt.show()
matplotlib add arrow and text on plot

Adding another line plot onto the same figure

To add another line plot into the same figure, we can call the plot() method again for another set of data. Here, new data is added in the form of lists (A and B) and plotted using the plot() method.

# Libraries/Modules import conventions
import matplotlib.pyplot as plt  

# For interactive matplotlib sessions, turn on the matplotlib inline mode
%matplotlib inline

# Dummy Data
X = [1, 2, 3, 4]
Y = [2, 4, 6, 8]
A = [1, 2, 3, 4]
B = [1, 2, 3, 4]

# Defining the figure shape
fig = plt.figure(figsize = (10, 4)) # Width is 10 and height is 4

# plot() is used for plotting a line plot
plt.plot(X, Y, color = 'green', linewidth = 5)
plt.plot(A, B, color = 'red', linewidth = 5)

# Adding annotations
plt.annotate('This is a line', xy=(2.5, 5.5), xytext=(1.5, 7),
             arrowprops={'facecolor':'black', 'shrink':0.05},
             )

# Adding title, xlabel and ylabel
plt.title('A Basic Line Plot') #Title of the plot
plt.xlabel('X-axis') #X-Label
plt.ylabel('Y-axis') #Y-Label

# show() is used for displaying the plot
plt.show()
matplotlib two plots on same figure

Displaying a Legend on the Matplotlib Line Plot

Legends are used when more than one plot is made in the same figure. A legend can be displayed using Matplotlib’s legend() method.

# Libraries/Modules import conventions
import matplotlib.pyplot as plt  

# For interactive matplotlib sessions, turn on the matplotlib inline mode
%matplotlib inline

# Dummy Data
X = [1, 2, 3, 4]
Y = [2, 4, 6, 8]
A = [1, 2, 3, 4]
B = [1, 2, 3, 4]

# Defining the figure shape
fig = plt.figure(figsize = (10, 4)) # Width is 10 and height is 4

# plot() is used for plotting a line plot
plt.plot(X, Y, color = 'green', linewidth = 5)
plt.plot(A, B, color = 'red', linewidth = 5)

# Adding annotations
plt.annotate('This is a line', xy=(2.5, 5.5), xytext=(1.5, 7),
             arrowprops={'facecolor':'black', 'shrink':0.05},
             )

# Adding title, xlabel and ylabel
plt.title('A Basic Line Plot') #Title of the plot
plt.xlabel('X-axis') #X-Label
plt.ylabel('Y-axis') #Y-Label

# Giving labels to each line (to be shown in the legend)
plt.legend(['Green Line', 'Red Line'])

# show() is used for displaying the plot
plt.show()
matplotlib display legend on a plot

Plotting subplots in Matplotlib

Sometimes it is necessary to plot multiple plots within a single figure. In such cases, we use the subplots() function of Matplotlib which returns a tuple (figax), giving a single figure fig with an array of axes ax.

Let us plot the two lines shown in the previous example in two different plots using subplots():

# Libraries/Modules import conventions
import matplotlib.pyplot as plt  

# For interactive matplotlib sessions, turn on the matplotlib inline mode
%matplotlib inline

# Dummy Data
X = [1, 2, 3, 4]
Y = [2, 4, 6, 8]
A = [1, 2, 3, 4]
B = [1, 2, 3, 4]

# Defining the figure shape
fig, ax = plt.subplots(1, 2) # One row and two columns

# plot() is used for plotting a line plot
ax[0].plot(X, Y, color = 'green', linewidth = 5)
ax[1].plot(A, B, color = 'red', linewidth = 5)

# show() is used for displaying the plot
plt.show()
plotting subplots in matplotlib

Now you know the basics of Matplotlib plots and you can start plotting your own line plots as needed.

Starting from the next chapter, we will learn how to plot other kinds of plots using Matplotlib and not just line plots. Head over to the next chapter on ‘Plotting 2D Plots in Matplotlib‘ to learn about the different 2D plots available in Matplotlib.


Basics of MatplotlibBasics of Matplotlib

Do you want to learn Python, Data Science, and Machine Learning while getting certified? Here are some best selling Datacamp courses that we recommend you enroll in:

  1. Introduction to Python (Free Course) - 1,000,000+ students already enrolled!
  2. Introduction to Data Science  in Python- 400,000+ students already enrolled!
  3. Introduction to TensorFlow for Deep Learning with Python - 90,000+ students already enrolled!
  4. Data Science and Machine Learning Bootcamp with R - 70,000+ students already enrolled!

Leave a Comment