Matplotlib Intro
Matplotlib is the most widely used plotting library for Python. It turns lists and arrays of numbers into line charts, bar charts, scatter plots, histograms, heatmaps, 3D surfaces and almost any other static figure you can think of. Most other Python visualisation tools, including pandas' .plot() and seaborn, are built on top of it, so learning Matplotlib pays off everywhere.
Here is a complete program that draws a chart. Press ▶ Run and the figure appears under the text output:
import matplotlib.pyplot as plt
days = [1, 2, 3, 4, 5, 6, 7]
visitors = [120, 135, 160, 150, 190, 240, 210]
plt.plot(days, visitors)
plt.title("Website visitors per day")
plt.show()
print("Plotted", len(days), "days; busiest day:", days[visitors.index(max(visitors))])Plotted 7 days; busiest day: 6
Five lines of plotting code gave us a titled line chart with numbered axes. Matplotlib picked the axis ranges, the tick positions, the line colour and the figure size for us.
Why Matplotlib?
| Strength | What it means for you |
|---|---|
| Mature | Started by John D. Hunter in 2003; stable, well documented and battle-tested |
| Flexible | Every element (lines, ticks, labels, colours, spacing) can be customised |
| Many chart types | Lines, bars, scatter, pie, histograms, box plots, contours, images, 3D, polar … |
| Works with NumPy and pandas | Pass arrays, lists or DataFrame columns directly |
| Many outputs | PNG, SVG, PDF, interactive windows, Jupyter notebooks, web pages |
| Free and open source | BSD-style licence, developed by a large community |
How it is organised
Matplotlib has two layers you will meet throughout this course:
matplotlib.pyplot(imported asplt) is a convenient, MATLAB-like set of functions.plt.plot(),plt.title(),plt.show()always act on "the current figure", so short scripts stay short.- The object-oriented API works with explicit
FigureandAxesobjects (fig, ax = plt.subplots(), thenax.plot(...)). It is clearer when a figure has several panels, and it is what most real projects use.
Both draw exactly the same things. We start with pyplot and move to the object-oriented style in the Figures & Axes lesson.
Matplotlib works with NumPy
Plotting functions accept plain Python lists, but in practice data usually lives in NumPy arrays. NumPy lets you compute a whole curve in one expression:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2 * np.pi, 100) # 100 evenly spaced points
y = np.sin(x)
plt.plot(x, y)
plt.title("One period of a sine wave")
plt.show()
print("Points:", x.size)
print(f"Highest value: {y.max():.3f}")Points: 100
Highest value: 1.000
np.linspace(start, stop, n) creates n evenly spaced numbers, and np.sin is applied to every element at once. Matplotlib then joins the 100 points with straight segments, which look like a smooth curve.
How the playground shows figures
In a desktop Python script, plt.show() opens a window. In a Jupyter notebook the figure appears below the cell. In this course the code runs in your browser (Pyodide), and every figure that is still open when the program ends is drawn as an image under the text output. We still call plt.show() in the examples so that they work unchanged on your own computer.
Because a picture has no text output, each example also prints a short line describing what it drew, such as a count of points or a value read back from the chart. This makes the examples easy to check.
Note: Matplotlib is a third-party package. On your own machine install it with
pip install matplotlib(NumPy comes with it). In the playground it is already available.
What you will learn
The first part of the course follows the classic tutorial path: getting started, the pyplot interface, plotting points and lines, markers and line styles, labels, grids, subplots, scatter plots, bar charts, histograms and pie charts. After that we go further: the object-oriented API, colours and colormaps, style sheets, legends, tick control and log scales, annotations, error bars, filled areas, box and violin plots, heatmaps, contour and 3D plots, twin axes, dates, plotting pandas data and saving figures. The course ends with exercises and a mini project where you build a small dashboard.
Test yourself
What is the conventional way to import Matplotlib's plotting interface?
- import matplotlib as plt
- import matplotlib.pyplot as plt
- from matplotlib import plot
- import pyplot
Which libraries are built on top of Matplotlib?
- NumPy and SciPy
- pandas plotting and seaborn
- Django and Flask
- None, Matplotlib is standalone only
What does np.linspace(0, 10, 5) produce?
- 5 random numbers between 0 and 10
- The numbers 0 to 10 in steps of 5
- 5 evenly spaced numbers from 0 to 10
- An array of length 10