Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Matplotlib

A plotting library. The pyplot module provides a MATLAB-like interface for creating figures. plt.show() renders the current figure to a window.

Line Plot

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.plot(x, y)
plt.title("Sine Wave")
plt.xlabel("x")
plt.ylabel("sin(x)")
plt.show()

Scatter Plot

import matplotlib.pyplot as plt

scores = [52, 66, 74, 88, 95]
hours = [2, 5, 7, 9, 11]

plt.scatter(hours, scores)
plt.title("Study Hours vs Score")
plt.xlabel("Hours")
plt.ylabel("Score")
plt.show()

Bar Plot

import matplotlib.pyplot as plt

names = ["Alice", "Bob", "Charlie"]
ages = [24, 30, 22]

plt.bar(names, ages)
plt.title("Ages")
plt.xlabel("Name")
plt.ylabel("Age")
plt.show()

Customization

# one figure, multiple plots
plt.plot(x, np.sin(x), label="sin")
plt.plot(x, np.cos(x), label="cos")
plt.legend()  # show labels
plt.grid()    # show grid lines
plt.show()