Free preview
12 minmatplotlib in Practice
Master the matplotlib object-oriented API, subplots, styling, and saving figures.
You've been using plt.plot(), plt.bar() — the quick 'functional' API. It works for single charts, but breaks down when you need:
- Multiple charts in one figure (subplots)
- Precise control over titles, colors, labels on each chart
- Saving to file at a specific size and resolution
The object-oriented API (fig, ax = plt.subplots()) solves all of this. It's how professional analysts write matplotlib.
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({'month': ['Jan','Feb','Mar','Apr'], 'revenue': [120,135,128,150], 'orders': [400,420,390,460]})
# OO API — two charts side by side
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))
ax1.plot(df['month'], df['revenue'], color='#2563EB', linewidth=2, marker='o')
ax1.set_title('Monthly Revenue')
ax1.set_ylabel('Revenue ($K)')
ax1.set_xlabel('Month')
ax2.bar(df['month'], df['orders'], color='#10B981')
ax2.set_title('Orders per Month')
ax2.set_ylabel('Orders')
plt.tight_layout() # prevents label overlap
plt.savefig('dashboard.png', dpi=150, bbox_inches='tight')
plt.show()Multiple choice
What does plt.subplots(2, 3) return?
- AA figure with 6 axes arranged in 2 rows × 3 columns
- BA figure with 2 charts stacked vertically
- C3 separate figures each with 2 subplots
- DAn error — subplots only accepts one argument
Annotating key data points:
fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(df['month'], df['revenue'], marker='o', linewidth=2)
# Find and annotate the peak
peak_idx = df['revenue'].idxmax()
peak_month = df.loc[peak_idx, 'month']
peak_val = df.loc[peak_idx, 'revenue']
ax.annotate(
f'Peak: ${peak_val}K',
xy=(peak_month, peak_val),
xytext=(0, 15),
textcoords='offset points',
ha='center',
arrowprops=dict(arrowstyle='->')
)
ax.set_title('Monthly Revenue with Peak Annotation')Annotations transform a chart from 'here is data' to 'here is the insight' — they do the mental work for the viewer.
Predict the output
What does this return?
import matplotlib.pyplot as plt
fig, axes = plt.subplots(2, 2)
print(axes.shape)- A(2, 2)
- B(4,)
- C(2,)
- D(1, 4)
Saving publication-quality figures:
# Standard for reports
plt.savefig('chart.png', dpi=150, bbox_inches='tight')
# For web (smaller file size)
plt.savefig('chart.png', dpi=96, bbox_inches='tight')
# For print (high resolution)
plt.savefig('chart.pdf', bbox_inches='tight') # PDF is vector — infinite resolution
# Check figure size before saving
print(fig.get_size_inches()) # (width, height) in inchesbbox_inches='tight' removes extra whitespace around the figure — always use it. dpi=150 is the sweet spot for screen display in reports.Fill in the blank
Set the title of an axes object ax:
ax.set_title('Monthly Revenue')
ax.set_ylabel('Revenue ($K)')
ax.set_xlabel('___')Multiple choice
You create a 3-subplot figure. plt.tight_layout() vs not calling it — what difference does it make?
- Atight_layout() is required for plt.savefig() to work
- Btight_layout() automatically adjusts subplot spacing so titles, labels, and axes don't overlap each other
- Ctight_layout() makes all subplots the same size
- Dtight_layout() sets the figure background to white