# Matplotlib tutorial for beginner

### Related tags

python tutorial matplotlib

# Matplotlib tutorial

## Nicolas P. Rougier

Sources are available from github

You can test your installation before the tutorial using the check-installation.py script.

## Introduction

matplotlib is probably the single most used Python package for 2D-graphics. It provides both a very quick way to visualize data from Python and publication-quality figures in many formats. We are going to explore matplotlib in interactive mode covering most common cases.

### IPython and the pylab mode

IPython is an enhanced interactive Python shell that has lots of interesting features including named inputs and outputs, access to shell commands, improved debugging and much more. When we start it with the command line argument -pylab (--pylab since IPython version 0.12), it allows interactive matplotlib sessions that have Matlab/Mathematica-like functionality.

### pyplot

pyplot provides a convenient interface to the matplotlib object-oriented plotting library. It is modeled closely after Matlab(TM). Therefore, the majority of plotting commands in pyplot have Matlab(TM) analogs with similar arguments. Important commands are explained with interactive examples.

## Simple plot

In this section, we want to draw the cosine and sine functions on the same plot. Starting from the default settings, we'll enrich the figure step by step to make it nicer.

The first step is to get the data for the sine and cosine functions:

import numpy as np

X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
C, S = np.cos(X), np.sin(X)


X is now a NumPy array with 256 values ranging from -π to +π (included). C is the cosine (256 values) and S is the sine (256 values).

To run the example, you can download each of the examples and run it using:

### Colormaps

All colormaps can be reversed by appending _r. For instance, gray_r is the reverse of gray.

If you want to know more about colormaps, see Documenting the matplotlib colormaps.

Name Appearance
autumn
bone
cool
copper
flag
gray
hot
hsv
jet
pink
prism
spectral
spring
summer
winter

Name Appearance
gist_earth
gist_gray
gist_heat
gist_ncar
gist_rainbow
gist_stern
gist_yarg

Name Appearance
BrBG
PiYG
PRGn
PuOr
RdBu
RdGy
RdYlBu
RdYlGn
Spectral

Name Appearance
Blues
BuGn
BuPu
GnBu
Greens
Greys
Oranges
OrRd
PuBu
PuBuGn
PuRd
Purples
RdPu
Reds
YlGn
YlGnBu
YlOrBr
YlOrRd

Name Appearance
Accent
Dark2
Paired
Pastel1
Pastel2
Set1
Set2
Set3

Name Appearance
afmhot
binary
brg
bwr
coolwarm
CMRmap
cubehelix
gnuplot
gnuplot2
ocean
rainbow
seismic
terrain
• #### A typo in your blog "Matplotlib tutorial"

I understand that I should not post a typo in your blog here, but this is the only way I can contact you, since your blog points here.

In your blog "Matplotlib tutorial", chapter "Simple Plot", section "Instantiating defaults", # savefig("../figures/exercice_2.png",dpi=72) could be changed to plt.savefig("../figures/exercice_2.png",dpi=72). You might have just missed plt in your code.

I really appreciate your tutorial. It's the best I could find on the web.

opened by JohnCoconut 2
• #### errata on http://www.labri.fr/perso/nrougier/teaching/matplotlib/#other-types-of-plots

Hi Nicolas, Great tutorial !

I've used version from http://www.labri.fr/perso/nrougier/teaching/matplotlib/ and there are errata in the #other-types-of-plots

http://www.labri.fr/perso/nrougier/teaching/matplotlib/#other-types-of-plots import maplotlib.pyplot as plt should be: import matplotlib.pyplot as plt in all examples

in GitHub version it is just fine

opened by LukeSkypewalker 2
• #### Python plot similar to Matlab's stackedplot()

Hello, Is there a plot function available in Python that is same as Matlab's stackedplot()? stackedplot() in Matlab can line plot several variables with the same X axis and are stacked vertically. Additionally, there is a scope in this plot that shows the value of all variables for a given X just by moving the cursor (please see the plot below). I have been able to generate subplots in Python with no issues, however, not able to add a scope like this that shows the value of all variables by moving the cursor. Is this feature available in Python?

Thanks much for your help in advance!

opened by addarnr 2
• #### Divergent and sequential colormaps

In the colormap section, it seems that you mistake divergent colormaps as sequential, and vice versa.

opened by smartlixx 2
• #### Update maplotlib to matlotlib

opened by cedricgilon 1
• #### Typo corrections

While reading your tutorial I noticed some minor errors. Here are the fixes.

opened by zormit 1
• #### Change drawing order

Change zorder-attribute of the lines so that they are drawn before the tick-labels. This moves the lines to the background and the tick-labels to the foreground.

opened by jruota 1
• #### Add edges in the pie chart exercise

Edges can be specified with a dictionary of arguments passed to the wedgeprops keyword.

opened by jruota 1
• #### Minor spellcheck

Hey! Thanks for writing a great, concise matplotlib tutorial. I fixed some minor spelling mistakes while reading through it, which you can merge if you like. Cheers.

opened by tommyod 1
• #### check-installation.py script syntax error

python check-installation.py Throws the following error:

File "check-installation.py", line 19 print("Check for numpy: ", end="") ^ SyntaxError: invalid syntax

opened by TayoO 1
• #### Remove references to pylab from the tutorial?

Salut,

I'm thinking you should maybe remove the (very) few references to pylab in your tutorial, as the offcial documentation now says "The pylab API (disapproved)"

opened by jypeter 1
• #### Drip drop animation in Jupyter notebook

Hi, thanks for sharing this excellent tutorial. I am learning it via Jupyter notebook, but I found that the drip drop animation code could not update automatically. Is there any suggestion? Indeed, it works in python IDE. Thanks again.

opened by LePingKYXK 1
• #### Hiding Spines

Hi, thank you for your tutorial, it's been really helpful!

In the Moving Spines section, you've used ax.spines['right'].set_color('none') to hide the axis. I wonder if ax.spines['right'].set_visible(False) would be a more elegant solution?

opened by joel-e-m-mitchell 1
• #### puzzle comment for dip

At "Instantiating defaults",

> # Create a new figure of size 8x6 points, using 100 dots per inch
>plt.figure(figsize=(8,6), dpi=80)


dpi means "dots per inch", why dpi in comment is 100, in parameter is 80 ?

opened by Sunqinying 1
• #### Python v2.7 error in Earthquakes.py

We discovered in the SciPy Tutorial that the url line should be updated for people running Python V 2.7

import urllib2 and line #26 should be changed to:

url = urllib2.urlopen(feed + "4.5_month.csv")

Cheers! Jen

opened by jbosch-noaa 0
##### Releases(1.0)
###### Nicolas P. Rougier
Researcher in computational and cognitive neuroscience supporting open source, open access and open science.
###### matplotlib: plotting with Python

Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. Check out our home page for more inform

13.1k Feb 18, 2021
###### Handout for the tutorial "Creating publication-quality figures with matplotlib"

Handout for the tutorial "Creating publication-quality figures with matplotlib"

1.7k Oct 20, 2021
###### Painlessly create beautiful matplotlib plots.

Announcement Thank you to everyone who has used prettyplotlib and made it what it is today! Unfortunately, I no longer have the bandwidth to maintain

1.6k Oct 16, 2021
###### :small_red_triangle: Ternary plotting library for python with matplotlib

python-ternary This is a plotting library for use with matplotlib to make ternary plots plots in the two dimensional simplex projected onto a two dime

476 Oct 23, 2021
###### :small_red_triangle: Ternary plotting library for python with matplotlib

python-ternary This is a plotting library for use with matplotlib to make ternary plots plots in the two dimensional simplex projected onto a two dime

391 Feb 17, 2021
5.3k Oct 18, 2021
###### Flexitext is a Python library that makes it easier to draw text with multiple styles in Matplotlib

Flexitext is a Python library that makes it easier to draw text with multiple styles in Matplotlib

54 Oct 16, 2021
###### This package creates clean and beautiful matplotlib plots that work on light and dark backgrounds

This package creates clean and beautiful matplotlib plots that work on light and dark backgrounds. Inspired by the work of Edward Tufte.

168 Oct 21, 2021
###### 🧇 Make Waffle Charts in Python.

PyWaffle PyWaffle is an open source, MIT-licensed Python package for plotting waffle charts. It provides a Figure constructor class Waffle, which coul

449 Oct 23, 2021
###### 🧇 Make Waffle Charts in Python.

PyWaffle PyWaffle is an open source, MIT-licensed Python package for plotting waffle charts. It provides a Figure constructor class Waffle, which coul

397 Feb 17, 2021
###### basemap - Plot on map projections (with coastlines and political boundaries) using matplotlib.

Basemap Plot on map projections (with coastlines and political boundaries) using matplotlib. ⚠️ Warning: this package is being deprecated in favour of

636 Oct 15, 2021
###### Easily convert matplotlib plots from Python into interactive Leaflet web maps.

mplleaflet mplleaflet is a Python library that converts a matplotlib plot into a webpage containing a pannable, zoomable Leaflet map. It can also embe

475 Sep 12, 2021
###### Attractors is a package for simulation and visualization of strange attractors.

attractors Attractors is a package for simulation and visualization of strange attractors. Installation The simplest way to install the module is via

35 Sep 15, 2021
###### Python package for hypergraph analysis and visualization.

The HyperNetX library provides classes and methods for the analysis and visualization of complex network data. HyperNetX uses data structures designed to represent set systems containing nested data and/or multi-way relationships. The library generalizes traditional graph metrics to hypergraphs.

164 Oct 13, 2021
###### A Python library for plotting hockey rinks with Matplotlib.

Hockey Rink A Python library for plotting hockey rinks with Matplotlib. Installation pip install hockey_rink Current Rinks The following shows the cus

6 Sep 14, 2021
###### Python histogram library - histograms as updateable, fully semantic objects with visualization tools. [P]ython [HYST]ograms.

physt P(i/y)thon h(i/y)stograms. Inspired (and based on) numpy.histogram, but designed for humans(TM) on steroids(TM). The goal is to unify different

115 Sep 28, 2021
###### 649 Pokémon palettes as CSVs, with a Python lib to turn names/IDs into palettes, or MatPlotLib compatible ListedColormaps.

PokePalette 649 Pokémon, broken down into CSVs of their RGB colour palettes. Complete with a Python library to convert names or Pokédex IDs into eithe

9 Sep 5, 2021
###### HW 02 for CS40 - matplotlib practice

HW 02 for CS40 - matplotlib practice project instructions https://github.com/mikeizbicki/cmc-csci040/tree/2021fall/hw_02 Drake Lyric Analysis Bar Char

2 Oct 23, 2021
###### Declarative statistical visualization library for Python

Altair http://altair-viz.github.io Altair is a declarative statistical visualization library for Python. With Altair, you can spend more time understa

7k Oct 15, 2021