Skip to content
Module 10 of 1250 min readBeginner

Plotting with matplotlib

Line, bar, scatter, histogram. Basic styling, subplots, and the explicit fig/ax pattern.

83%

Listen along

Read “Plotting with matplotlib” aloud

Plays in your browser using on-device text-to-speech — nothing leaves the page.

Learning objectives

By the end of this module, you should be able to:

  • 01Build matplotlib figures using the explicit fig, ax = plt.subplots() pattern
  • 02Apply the common geoms: line, scatter, bar, hist, boxplot
  • 03Compose multi-panel figures with subplots()
  • 04Recognise when to reach for seaborn (statistical defaults) or plotly (interactivity) instead

matplotlib is the foundation plotting library for Python. Its API is two-track: a pyplot 'state machine' interface that mimics MATLAB, and an explicit object-oriented interface that scales to complex figures. Modern practice uses the explicit fig/ax pattern even for simple plots.

The fig/ax pattern

python
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8, 5))
ax.plot(bankrates['month'], bankrates['lending_rate'], label='Lending')
ax.plot(bankrates['month'], bankrates['deposit_rate'], label='Deposit')
ax.set_xlabel('Month')
ax.set_ylabel('Rate (%)')
ax.set_title('Kenyan commercial bank rates, 2023-2024')
ax.legend()
plt.show()

Common plot types

python
ax.plot(x, y) # line
ax.scatter(x, y) # scatter
ax.bar(x, heights) # bar
ax.hist(values, bins=20) # histogram
ax.boxplot(arrays) # boxplot

Multiple subplots

python
fig, axes = plt.subplots(1, 2, figsize=(12, 4))
axes[0].plot(x, y1)
axes[0].set_title('Lending')
axes[1].plot(x, y2)
axes[1].set_title('Deposit')
fig.tight_layout()

Pandas .plot()

Pandas wraps matplotlib in a more concise API. For exploratory plots, df.plot() is hard to beat.

python
bankrates.plot(x='month', y=['lending_rate', 'deposit_rate'])

Styling — keep it minimal

Resist the urge to over-style. The defaults in modern matplotlib are good. Add labels, a title, and a legend; resize for the medium; export to PNG or SVG.

When to reach for seaborn or plotly

Seaborn is matplotlib with smarter statistical defaults — quicker for distributions, regressions, and faceted plots. Plotly is interactive and ideal for dashboards. Both build on top of matplotlib for the underlying engine.

Exercise

Plot a line chart of bankrates['month'] vs bankrates['lending_rate'].

Key takeaways

  • Use the explicit fig/ax pattern, not the pyplot state machine — it scales to complex figures
  • Defaults in modern matplotlib are good; resist the urge to over-style
  • df.plot() is the fastest path for exploratory pandas plots — it wraps matplotlib
  • Save with plt.savefig('out.png', dpi=300, bbox_inches='tight') for publication-quality output
Loading progress…
LeadAfrikPublic Economics Hub