Code of the Day
IntermediateVisualisation

Matplotlib essentials

Create figures with plt.subplots(), plot line and bar charts, set titles and labels, and understand the figure/axes model.

Data ScienceIntermediate10 min read
Recommended first
By the end of this lesson you will be able to:
  • 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.

Python — editable, runs in your browser

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

Python — editable, runs in your browser

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

MethodWhat 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.

Finished reading? Mark it complete to track your progress.

On this page