The Bare Minimum Guide to Matplotlib

Read a more detailed version of this post on my personal blog by clicking here

Stefan Hrouda-Rasmussen

Getting started

Object-oriented approach

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, num=10)
y = np.sin(x)
fig = plt.figure()
ax = fig.add_subplot()
ax.scatter(x, y)
plt.show()

Line charts

from scipy.stats import norm
x = np.linspace(-4, 4, num=100)
fig = plt.figure(figsize=(8, 5))
ax = fig.add_subplot()
ax.plot(x, norm.pdf(x, loc=-1, scale=1), color="magenta")
ax.plot(x, norm.pdf(x, loc=0, scale=1), color=(0.85, 0.64, 0.12))
ax.plot(x, norm.pdf(x, loc=1, scale=1), color="#228B22")
plt.show()
x = np.linspace(-6, 6, num=100)fig = plt.figure(figsize=(8, 5))
ax = fig.add_subplot()
ax.plot(x, norm.pdf(x, loc=-3, scale=1), linestyle="solid")
ax.plot(x, norm.pdf(x, loc=-1, scale=1), linestyle="dotted")
ax.plot(x, norm.pdf(x, loc=1, scale=1), linestyle="dashed")
ax.plot(x, norm.pdf(x, loc=3, scale=1), linestyle="dashdot")
plt.show()
x = np.linspace(-2, 9, num=100)fig = plt.figure(figsize=(8, 5))
ax = fig.add_subplot()
for i in range(1,7):
ax.plot(
x, norm.pdf(x, loc=i, scale=1), color="black", linewidth=i/2
)
plt.show()

Scatter charts

x = np.linspace(-4, 4, num=20)
y1 = x
y2 = -y1
y3 = y1**2
fig = plt.figure(figsize=(8, 5))
ax = fig.add_subplot()
ax.scatter(x=x, y=y1, marker="v", s=1)
ax.scatter(x=x, y=y2, marker="X", s=5)
ax.scatter(x=x, y=y3, marker="s", s=10)
plt.show()
x = np.linspace(-2, 2, num=20)
y = x ** 3 - x
fig = plt.figure(figsize=(8, 5))
ax = fig.add_subplot()
ax.plot(x, y, 'H-g')plt.show()

Histograms

x = np.random.randn(10000)fig = plt.figure(figsize=(8, 5))
ax = fig.add_subplot()
ax.hist(x)plt.show()
x1 = np.random.randn(10000)-1
x2 = np.random.randn(10000)+1
fig = plt.figure(figsize=(8, 5))
ax = fig.add_subplot()
ax.hist(
x1,
color='turquoise',
edgecolor='none',
bins=50,
alpha=0.5,
density=True
)
ax.hist(
x2,
color='magenta',
edgecolor='none',
bins=200,
alpha=0.5,
density=True
)
plt.show()

Legends

x = np.linspace(-2, 2, num=100)
y1 = x
y2 = x**2
fig = plt.figure(figsize=(8, 5))
ax = fig.add_subplot()
ax.plot(x, y1, color='turquoise', label='First')
ax.plot(x, y2, color='magenta', label='Second')
ax.legend()plt.show()
x = np.linspace(-2, 2, num=100)
y1 = x
y2 = np.sin(x)+np.cos(x)
y3 = x**2
fig = plt.figure(figsize=(8, 5))
ax = fig.add_subplot()
ax.plot(x, y1, color='turquoise', label='First')
ax.plot(x, y2, color='magenta', label='Second')
ax.plot(x, y3, color='forestgreen', label='Third')
ax.legend(loc='lower center', frameon=False, ncol=3)plt.show()

Final tips