Matplotlib essentials
Create figures with plt.subplots(), plot line and bar charts, set titles and labels, and understand the figure/axes model.
- Create a figure and axes object with plt.subplots()
- Plot a line chart and a bar chart on an axes
- Set title, axis labels, and a legend
- Explain the difference between the figure and the axes
Matplotlib is the foundational plotting library for Python. Every other visualisation library — seaborn, pandas plot, plotly static — either wraps matplotlib or takes heavy inspiration from it. Understanding its core model makes everything else easier.
The figure and axes model
Matplotlib separates the figure (the whole canvas) from the axes (a
single plot area within the canvas). A figure can contain multiple axes — that
is what subplots are. Most beginners use plt.plot() directly, which implicitly
creates both. Learning fig, ax = plt.subplots() instead gives you explicit
control and lets you build multi-panel layouts later.
ax.plot() draws a line. marker= adds a point symbol at each data value.
linestyle="--" makes a dashed line. label= registers a name for the legend —
but the legend only appears after ax.legend() is called.
Bar charts
Setting ax.set_ylim(0, ...) explicitly anchors the y-axis at zero, which
is good practice for bar charts. Readers expect bars to start from zero; a
truncated axis changes the perceived ratio between bars without changing the
numbers.
Key methods to remember
| Method | What it does |
|---|---|
plt.subplots(figsize=) | Create figure + axes, set canvas size in inches |
ax.plot(x, y) | Line plot |
ax.bar(x, height) | Bar chart |
ax.set_title(str) | Chart title |
ax.set_xlabel/ylabel(str) | Axis labels |
ax.legend() | Draw the legend from registered labels |
plt.tight_layout() | Fix label clipping |
plt.savefig(path) | Save to file |
Where to go next
Next: seaborn statistical — how seaborn builds on matplotlib to produce statistical plots (pairplot, heatmap, catplot) directly from DataFrames with less boilerplate.
Choosing a chart
Match your chart type to the question you are asking — bar for comparison, line for trend, scatter for relationship, histogram for distribution, box for spread.
Seaborn statistical plots
Seaborn understands DataFrames and adds statistical awareness — learn when pairplot, heatmap, catplot, and boxplot each reveal insight.