Visualization with Matplotlib | Python Data Science Handbook (2025)

< Further Resources | Contents | Simple Line Plots >

Visualization with Matplotlib | Python Data Science Handbook (1)

We'll now take an in-depth look at the Matplotlib package for visualization in Python.Matplotlib is a multi-platform data visualization library built on NumPy arrays, and designed to work with the broader SciPy stack.It was conceived by John Hunter in 2002, originally as a patch to IPython for enabling interactive MATLAB-style plotting via gnuplot from the IPython command line.IPython's creator, Fernando Perez, was at the time scrambling to finish his PhD, and let John know he wouldn’t have time to review the patch for several months.John took this as a cue to set out on his own, and the Matplotlib package was born, with version 0.1 released in 2003.It received an early boost when it was adopted as the plotting package of choice of the Space Telescope Science Institute (the folks behind the Hubble Telescope), which financially supported Matplotlib’s development and greatly expanded its capabilities.

One of Matplotlib’s most important features is its ability to play well with many operating systems and graphics backends.Matplotlib supports dozens of backends and output types, which means you can count on it to work regardless of which operating system you are using or which output format you wish.This cross-platform, everything-to-everyone approach has been one of the great strengths of Matplotlib.It has led to a large user base, which in turn has led to an active developer base and Matplotlib’s powerful tools and ubiquity within the scientific Python world.

In recent years, however, the interface and style of Matplotlib have begun to show their age.Newer tools like ggplot and ggvis in the R language, along with web visualization toolkits based on D3js and HTML5 canvas, often make Matplotlib feel clunky and old-fashioned.Still, I'm of the opinion that we cannot ignore Matplotlib's strength as a well-tested, cross-platform graphics engine.Recent Matplotlib versions make it relatively easy to set new global plotting styles (see Customizing Matplotlib: Configurations and Style Sheets), and people have been developing new packages that build on its powerful internals to drive Matplotlib via cleaner, more modern APIs—for example, Seaborn (discussed in Visualization With Seaborn), ggpy, HoloViews, Altair, and even Pandas itself can be used as wrappers around Matplotlib's API.Even with wrappers like these, it is still often useful to dive into Matplotlib's syntax to adjust the final plot output.For this reason, I believe that Matplotlib itself will remain a vital piece of the data visualization stack, even if new tools mean the community gradually moves away from using the Matplotlib API directly.

General Matplotlib Tips

Before we dive into the details of creating visualizations with Matplotlib, there are a few useful things you should know about using the package.

Importing Matplotlib

Just as we use the np shorthand for NumPy and the pd shorthand for Pandas, we will use some standard shorthands for Matplotlib imports:

The plt interface is what we will use most often, as we shall see throughout this chapter.

Setting Styles

We will use the plt.style directive to choose appropriate aesthetic styles for our figures.Here we will set the classic style, which ensures that the plots we create use the classic Matplotlib style:

Throughout this section, we will adjust this style as needed.Note that the stylesheets used here are supported as of Matplotlib version 1.5; if you are using an earlier version of Matplotlib, only the default style is available.For more information on stylesheets, see Customizing Matplotlib: Configurations and Style Sheets.

show() or No show()? How to Display Your Plots

A visualization you can't see won't be of much use, but just how you view your Matplotlib plots depends on the context.The best use of Matplotlib differs depending on how you are using it; roughly, the three applicable contexts are using Matplotlib in a script, in an IPython terminal, or in an IPython notebook.

Plotting from a script

If you are using Matplotlib from within a script, the function plt.show() is your friend.plt.show() starts an event loop, looks for all currently active figure objects, and opens one or more interactive windows that display your figure or figures.

So, for example, you may have a file called myplot.py containing the following:

# ------- file: myplot.py ------import matplotlib.pyplot as pltimport numpy as npx = np.linspace(0, 10, 100)plt.plot(x, np.sin(x))plt.plot(x, np.cos(x))plt.show()

You can then run this script from the command-line prompt, which will result in a window opening with your figure displayed:

$ python myplot.py

The plt.show() command does a lot under the hood, as it must interact with your system's interactive graphical backend.The details of this operation can vary greatly from system to system and even installation to installation, but matplotlib does its best to hide all these details from you.

One thing to be aware of: the plt.show() command should be used only once per Python session, and is most often seen at the very end of the script.Multiple show() commands can lead to unpredictable backend-dependent behavior, and should mostly be avoided.

Plotting from an IPython shell

It can be very convenient to use Matplotlib interactively within an IPython shell (see IPython: Beyond Normal Python).IPython is built to work well with Matplotlib if you specify Matplotlib mode.To enable this mode, you can use the %matplotlib magic command after starting ipython:

In [1]: %matplotlibUsing matplotlib backend: TkAggIn [2]: import matplotlib.pyplot as plt

At this point, any plt plot command will cause a figure window to open, and further commands can be run to update the plot.Some changes (such as modifying properties of lines that are already drawn) will not draw automatically: to force an update, use plt.draw().Using plt.show() in Matplotlib mode is not required.

Plotting from an IPython notebook

The IPython notebook is a browser-based interactive data analysis tool that can combine narrative, code, graphics, HTML elements, and much more into a single executable document (see IPython: Beyond Normal Python).

Plotting interactively within an IPython notebook can be done with the %matplotlib command, and works in a similar way to the IPython shell.In the IPython notebook, you also have the option of embedding graphics directly in the notebook, with two possible options:

  • %matplotlib notebook will lead to interactive plots embedded within the notebook
  • %matplotlib inline will lead to static images of your plot embedded in the notebook

For this book, we will generally opt for %matplotlib inline:

After running this command (it needs to be done only once per kernel/session), any cell within the notebook that creates a plot will embed a PNG image of the resulting graphic:

Saving Figures to File

One nice feature of Matplotlib is the ability to save figures in a wide variety of formats.Saving a figure can be done using the savefig() command.For example, to save the previous figure as a PNG file, you can run this:

We now have a file called my_figure.png in the current working directory:

To confirm that it contains what we think it contains, let's use the IPython Image object to display the contents of this file:

In savefig(), the file format is inferred from the extension of the given filename.Depending on what backends you have installed, many different file formats are available.The list of supported file types can be found for your system by using the following method of the figure canvas object:

Note that when saving your figure, it's not necessary to use plt.show() or related commands discussed earlier.

Two Interfaces for the Price of One

A potentially confusing feature of Matplotlib is its dual interfaces: a convenient MATLAB-style state-based interface, and a more powerful object-oriented interface. We'll quickly highlight the differences between the two here.

MATLAB-style Interface

Matplotlib was originally written as a Python alternative for MATLAB users, and much of its syntax reflects that fact.The MATLAB-style tools are contained in the pyplot (plt) interface.For example, the following code will probably look quite familiar to MATLAB users:

It is important to note that this interface is stateful: it keeps track of the "current" figure and axes, which are where all plt commands are applied.You can get a reference to these using the plt.gcf() (get current figure) and plt.gca() (get current axes) routines.

While this stateful interface is fast and convenient for simple plots, it is easy to run into problems.For example, once the second panel is created, how can we go back and add something to the first?This is possible within the MATLAB-style interface, but a bit clunky.Fortunately, there is a better way.

Object-oriented interface

The object-oriented interface is available for these more complicated situations, and for when you want more control over your figure.Rather than depending on some notion of an "active" figure or axes, in the object-oriented interface the plotting functions are methods of explicit Figure and Axes objects.To re-create the previous plot using this style of plotting, you might do the following:

For more simple plots, the choice of which style to use is largely a matter of preference, but the object-oriented approach can become a necessity as plots become more complicated.Throughout this chapter, we will switch between the MATLAB-style and object-oriented interfaces, depending on what is most convenient.In most cases, the difference is as small as switching plt.plot() to ax.plot(), but there are a few gotchas that we will highlight as they come up in the following sections.

< Further Resources | Contents | Simple Line Plots >

Visualization with Matplotlib | Python Data Science Handbook (2)

Visualization with Matplotlib | Python Data Science Handbook (2025)

FAQs

Is matplotlib used for data science? ›

Data visualization is a crucial aspect of data analysis, enabling data scientists and analysts to present complex data in a more understandable and insightful manner. One of the most popular libraries for data visualization in Python is Matplotlib.

Which interface of matplotlib is used for data visualization? ›

PyPlot is the graphical module in matplotlib which is mostly used for data visualisation, importing PyPlot is sufficient to work around data visualisation.

What is the PLT show command in Python? ›

plt. show() starts an event loop, looks for all currently active figure objects, and opens one or more interactive windows that display your figure or figures. The plt. show() command does a lot under the hood, as it must interact with your system's interactive graphical backend.

How to visualize data in Python using matplotlib? ›

The function used is `plot()`, which is a basic function in Matplotlib. To create this graph, we use two libraries, Matplotlib and NumPy. NumPy is used to calculate the sine and cosine values, and the `arange` function generates a list from 0 to 2 Pi with an interval of 0.1 between each value.

Is Matplotlib still relevant? ›

As with many things, this depends entirely on your requirements. If you have very specific needs, or like to be able to precisely configure every element of your plot, then I would argue Matplotlib is still far and away the single best library available for plotting in the world of Python.

Why is Seaborn better than Matplotlib? ›

Seaborn is built on top of Matplotlib and provides a higher-level interface for creating statistical graphics. This means that Seaborn requires less code to create complex visualizations compared to Matplotlib.

Is matplotlib related to MATLAB? ›

Matplotlib is a library for making 2D plots of arrays in Python. Although it has its origins in emulating the MATLAB graphics commands, it is independent of MATLAB, and can be used in a Pythonic, object-oriented way.

How to read and display image in Python using matplotlib? ›

How to read a image using matplotlib?
  1. Recipe Objective. How to read a image using matplotlib?
  2. Step 1- Importing Libraries. import matplotlib.pyplot as plt import matplotlib.image as img.
  3. Step 2- Reading Image. Reading Image from the drive. If you are running the code in local write the path of your local system.
Jan 25, 2021

Why import matplotlib pyplot as plt? ›

import matplotlib. pyplot as plt is shorter but no less clear. import matplotlib. pyplot as plt gives an unfamiliar reader a hint that pyplot is a module, rather than a function which could be incorrectly assumed from the first form.

What are the five types of plot of matplotlib? ›

It can create different types of visualization reports like line plots, scatter plots, histograms, bar charts, pie charts, box plots, and many more different plots.

What is the difference between PLT scatter and PLT plot? ›

The primary difference of plt. scatter from plt. plot is that it can be used to create scatter plots where the properties of each individual point (size, face color, edge color, etc.) can be individually controlled or mapped to data.

What is the first step when plotting with matplotlib? ›

Following steps were followed:
  • Define the x-axis and corresponding y-axis values as lists.
  • Plot them on canvas using . plot() function.
  • Give a name to x-axis and y-axis using . xlabel() and . ylabel() functions.
  • Give a title to your plot using . title() function.
  • Finally, to view your plot, we use . show() function.
Jan 4, 2022

Matplotlib: Master Data Visualization in PythonDataScientest.comhttps://datascientest.com ›

For instance, you can create plots, histograms, bar charts, and various types of graphs with just a few lines of code. It's a comprehensive tool that enable...
We'll use the Numpy package imported in the third line for numerical computations. We'll also work with the date module for date manipulations when plot...
When to prefer other libraries? Objectives. Be able to create simple plots with Matplotlib and tweak them. Know about object-oriented vs pyplot interfaces of Ma...

What is Matplotlib mostly used for? ›

Matplotlib is a popular data visualization library in Python. It's often used for creating static, interactive, and animated visualizations in Python. Matplotlib allows you to generate plots, histograms, bar charts, scatter plots, etc., with just a few lines of code.

Which Python library is used for data science? ›

Pandas (Python data analysis) is a must in the data science life cycle. It is the most popular and widely used Python library for data science, along with NumPy in matplotlib. With around 17,00 comments on GitHub and an active community of 1,200 contributors, it is heavily used for data analysis and cleaning.

Is Matplotlib necessary for machine learning? ›

This is where Matplotlib, a robust plotting library in Python, becomes an essential tool for any machine learning practitioner.

Do you use Python in data science? ›

As one of the most popular data science programming languages, Python is an incredibly helpful tool with a variety of applications in the field. To succeed in this field, devs have to understand not only Python as a language itself, but also its frameworks, tools, and other skills associated with the field.

Top Articles
Latest Posts
Recommended Articles
Article information

Author: Delena Feil

Last Updated:

Views: 5595

Rating: 4.4 / 5 (65 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Delena Feil

Birthday: 1998-08-29

Address: 747 Lubowitz Run, Sidmouth, HI 90646-5543

Phone: +99513241752844

Job: Design Supervisor

Hobby: Digital arts, Lacemaking, Air sports, Running, Scouting, Shooting, Puzzles

Introduction: My name is Delena Feil, I am a clean, splendid, calm, fancy, jolly, bright, faithful person who loves writing and wants to share my knowledge and understanding with you.