A first plot

matplotlib in the notebook — import, draw, plt.show().

The notebook can draw matplotlib figures in the cell. Import it, draw, then call plt.show(). The first run may take a few seconds while the library loads.

Goal

Plot a simple line and a bar chart. If the cell is slow, wait; do not spam Run.

Line

import matplotlib.pyplot as plt

xs = [0, 1, 2, 3, 4, 5]
ys = [0, 1, 4, 9, 16, 25]
plt.figure()
plt.plot(xs, ys, marker="o")
plt.title("n squared")
plt.xlabel("n")
plt.ylabel("n²")
plt.show()

Bar

import matplotlib.pyplot as plt

cities = ["Nairobi", "Mombasa", "Kisumu"]
units = [17, 13, 14]
plt.figure()
plt.bar(cities, units)
plt.title("Units by city")
plt.show()

numpy helper

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 80)
plt.figure()
plt.plot(x, np.sin(x), label="sin")
plt.plot(x, np.cos(x), label="cos")
plt.legend()
plt.title("sin and cos")
plt.show()
Pitfall

Without plt.show(), the figure may not appear. Do not paste Jupyter %matplotlib inline — this notebook does not use magics.