Python - Matplotlib
Overview
Estimated time: 25–35 minutes
Matplotlib is a comprehensive plotting library. Learn the object model (figure/axes), common plot types, and saving figures.
Learning Objectives
- Create figures and axes; plot lines, bars, and scatter.
- Style plots (labels, legends, titles) and save to files.
Examples
import matplotlib.pyplot as plt
x = [1,2,3,4]
y = [10, 12, 8, 15]
fig, ax = plt.subplots()
ax.plot(x, y, marker='o', label='series')
ax.set_title('Example')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.legend()
fig.savefig('plot.png', dpi=150)
Guidance & Patterns
- Use the OO API (
fig, ax = plt.subplots()
) for clarity and composition. - Prefer consistent styling and labeling; keep fonts legible.
Best Practices
- Export vector formats (SVG/PDF) for print; PNG for web.
- Use tight_layout/constrained_layout to manage spacing.
Exercises
- Create a subplot grid with two different chart types sharing an x-axis.
- Style a chart for publication quality and save as SVG.