Data Visualization with Matplotlib
A chart shows a pattern that a table of numbers hides. Matplotlib is the standard plotting library for Python, and pandas uses it behind the scenes.
Charts need a place to draw, so the examples in this lesson are for your own computer. Install Python, run pip install matplotlib pandas, and paste the code into a Jupyter notebook or a .py file.
The basic pattern
import matplotlib.pyplot as plt
months = ["Jan", "Feb", "Mar", "Apr", "May"]
revenue = [2550, 1410, 1300, 2380, 1690]
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(months, revenue, marker="o")
ax.set_title("Monthly revenue")
ax.set_xlabel("Month")
ax.set_ylabel("Revenue")
plt.show()
plt.subplots() returns a figure (the whole image) and an axes (one chart inside it). You call plotting methods on the axes.
Choosing a chart
| Question | Chart | Method |
|---|---|---|
| How does a value change over time? | Line | ax.plot |
| How do categories compare? | Bar | ax.bar or ax.barh |
| How are two numbers related? | Scatter | ax.scatter |
| How are values distributed? | Histogram | ax.hist |
| How do groups differ in spread? | Box plot | ax.boxplot |
Bar chart
categories = ["Computers", "Accessories", "Office"]
revenue = [5600, 1050, 210]
fig, ax = plt.subplots()
ax.barh(categories, revenue)
ax.set_title("Revenue by category")
ax.invert_yaxis() # largest at the top
plt.show()
Histogram and scatter
import numpy as np
rng = np.random.default_rng(1)
heights = rng.normal(170, 8, 500)
weights = heights * 0.9 - 85 + rng.normal(0, 6, 500)
fig, (left, right) = plt.subplots(1, 2, figsize=(10, 4))
left.hist(heights, bins=25)
left.set_title("Distribution of height")
right.scatter(heights, weights, alpha=0.4)
right.set_title("Height and weight")
plt.show()
plt.subplots(1, 2) creates two charts side by side.
Plotting straight from pandas
A DataFrame has a plot method, which is usually the quickest route.
import pandas as pd
df = pd.DataFrame({
"category": ["Computers", "Accessories", "Office"],
"revenue": [5600, 1050, 210],
})
df.plot(kind="bar", x="category", y="revenue", legend=False, title="Revenue by category")
plt.tight_layout()
plt.savefig("revenue.png", dpi=150)
savefig writes the chart to a file for a report or slide.
Making a chart honest and readable
- Give every chart a title and label both axes, with units.
- Start the value axis of a bar chart at zero.
- Sort bars by value unless the categories have a natural order.
- Use colour to highlight, not to decorate.
- Remove anything that does not help the reader: extra gridlines, borders, legends for a single series.
Other libraries
Seaborn builds on Matplotlib and produces statistical charts in one line. Plotly produces interactive charts for web pages. Both follow the same ideas as this lesson.
Practice
On your computer, plot the price column of the products DataFrame from the previous lesson as a sorted horizontal bar chart.