Matplotlib Installation and Import

MatplotlibBeginner
Practice Now

Introduction

Welcome to your first hands-on lab with Matplotlib! Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. It is the foundation for many other data visualization libraries and is an essential tool for any data scientist or analyst.

Before starting this course, you should have basic Python programming skills and ensure that Python is properly configured in your system PATH. If you haven't learned Python yet, you can start from our Python Learning Path. Additionally, you should have NumPy and Pandas installed as they are essential prerequisites for scikit-learn operations. If you need to learn these libraries, you can explore our NumPy Learning Path and Pandas Learning Path.

In this lab, you will learn the most basic and crucial first steps for using Matplotlib. We will cover how to ensure Matplotlib is installed, how to import it into your Python scripts using the standard conventions, and how to create and save a simple, empty plot. By the end of this lab, you will have a foundational understanding of how to set up your environment for any Matplotlib project.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a intermediate level lab with a 80% completion rate. It has received a 100% positive review rate from learners.

Install Matplotlib using pip

In this step, you will learn how to install Matplotlib. As a third-party library, it is not included with a standard Python installation. It must be installed using pip, the package installer for Python.

The standard command to install it is pip install matplotlib. However, for your convenience, Matplotlib has already been installed in this lab environment. Your task is to verify the installation.

You can check the details of an installed package using the pip show command. Run the following command in the terminal to confirm that matplotlib is installed.

pip show matplotlib
pip show matplotlib

You should see output similar to the following, confirming the installation and showing its version and location. The exact version and location may differ slightly.

Name: matplotlib
Version: 3.10.0
Summary: Python plotting package
Home-page: https://un5yc902zhx2m3pgt32g.julianrbryant.com
Author: John D. Hunter, Michael Droettboom
Author-email: matplotlib-users@python.org
License: PSF
Location: /usr/local/lib/python3.10/dist-packages
Requires: contourpy, cycler, fonttools, kiwisolver, numpy, packaging, pillow, pyparsing, python-dateutil
Required-by:

Import matplotlib.pyplot as plt

In this step, you will import the necessary Matplotlib module into your Python script. The core of Matplotlib's plotting functionality is contained within the pyplot module.

By convention, matplotlib.pyplot is imported with the alias plt. This industry-standard alias makes your code more concise and readable, as you can type plt.function() instead of matplotlib.pyplot.function().

First, locate the main.py file in the file explorer on the left side of your IDE. Double-click it to open it in the editor.

Now, add the following line of code to main.py:

import matplotlib.pyplot as plt

This line tells Python to find the matplotlib.pyplot library and make its functions available in your script under the shorter name plt.

Verify import with version check

In this step, you will verify that the library was imported correctly by checking its version from within the script. Accessing the __version__ attribute is a common and simple way to confirm that a Python library is successfully loaded and accessible.

Modify your main.py file to add a print statement. This will execute the code and display the Matplotlib version in the terminal.

Your main.py file should now look like this:

import matplotlib
import matplotlib.pyplot as plt

print(matplotlib.__version__)

Suggestion: You can copy the above code into your code editor, then carefully read each line of code to understand its function. If you need further explanation, you can click the "Explain Code" button 👆. You can interact with Labby for personalized help.

Matplotlib version check code

Now, save the file and run it from the terminal using the python3 command:

python3 main.py

After running the script, you will see the installed version number printed to the terminal.

3.10.0

This confirms that your Python script can successfully import and use the Matplotlib library.

Create a simple figure object

In this step, you will create the fundamental objects for any plot: a Figure and an Axes.

  • A Figure is the top-level container for all the plot elements. You can think of it as the entire canvas or window.
  • An Axes is the area where data is plotted with x-axis and y-axis. A figure can contain one or more axes.

The most common way to create a figure and a set of subplots (axes) is with the plt.subplots() function. This function returns a tuple containing a Figure and an Axes object (or an array of Axes objects).

Modify your main.py file. You can remove the print statement and add the code to create a plot and save it.

import matplotlib.pyplot as plt

## Create a Figure and an Axes object
fig, ax = plt.subplots()

## Save the figure to a file
plt.savefig('empty_plot.png')

In this code, fig, ax = plt.subplots() creates a figure and a single axes. Since we are in a web-based environment that cannot display a GUI window, we use plt.savefig('empty_plot.png') to save the contents of the figure to an image file named empty_plot.png.

Now, run the script from the terminal:

python3 main.py

This command will not produce any output in the terminal. Instead, it will create a new file named empty_plot.png in your /home/labex/project directory.

Display an empty plot using plt.show()

In the previous step, you generated an image file of your plot. In this step, you will learn how to view it within the LabEx environment.

As mentioned, we cannot use plt.show() to open a pop-up window. The plt.savefig() function is our method for "displaying" the plot by writing it to a file.

To see your creation, look at the file explorer panel on the left side of the IDE. You should see the empty_plot.png file that was generated by your script.

Double-click on empty_plot.png.

Empty plot

This will open the image in a new tab inside the IDE. You should see a simple, blank plot with an x-axis and a y-axis. This is your first successfully generated Matplotlib figure!

This step does not require you to write any new code or run any commands. It is purely for observing the result of your work from the previous step.

Summary

Congratulations! You have successfully completed this introductory lab on Matplotlib setup.

In this lab, you have learned the essential first steps for working with this powerful visualization library. You have covered:

  • How to verify the installation of Matplotlib using pip.
  • The standard convention for importing the library: import matplotlib.pyplot as plt.
  • How to create a basic Figure and Axes object, the building blocks of all plots, using plt.subplots().
  • How to save a plot to an image file with plt.savefig(), a crucial skill for non-GUI environments.

You are now prepared to move on to more exciting labs where you will learn to plot actual data and customize your visualizations.