Module 16 · External Libraries and APIs — topic 7 of 12
Matplotlib introduction
Charts with Matplotlib: the figure and axes model, line, bar and scatter plots, titles, labels and legends, subplots, and saving charts to image files.
Learning objectives
- Create line, bar and scatter charts
- Label charts with titles, axes labels and legends
- Arrange subplots and save figures
Definition
Matplotlib is Python's foundational plotting library. A Figure is the whole image; it contains one or more Axes (individual plots) on which you draw lines, bars, points and text.
Introduction
A chart often explains data faster than any table. Matplotlib turns lists, NumPy arrays and pandas columns into publication-quality images.
Why it matters
Visualising data reveals trends and outliers, and charts are how analysis results are usually shared.
Detailed explanation
Install with python -m pip install matplotlib and import matplotlib.pyplot as plt.
The recommended style is fig, ax = plt.subplots(), then call methods on ax: ax.plot, ax.bar, ax.scatter.
Label every chart: ax.set_title, ax.set_xlabel, ax.set_ylabel; pass label= to plotting calls and call ax.legend().
plt.subplots(rows, cols) creates a grid of Axes; sharex=True aligns their x-axes. fig.tight_layout() prevents overlapping labels.
fig.savefig("chart.png", dpi=150) writes an image (PNG, SVG, PDF...). plt.show() opens a window in interactive sessions.
On servers without a display, select the non-interactive Agg backend with matplotlib.use("Agg") before importing pyplot.
pandas DataFrames have a .plot() method built on Matplotlib, handy for quick charts.
Syntax
- fig, ax = plt.subplots().
- Always label charts.
- savefig writes an image.
Code examples
A simple line chart
Requires Matplotlib. plt.show() opens a window with the chart.
A bar chart saved to a file
True Monthly sales 4
Requires Matplotlib. The Agg backend draws without opening a window.
More examples
Two related charts
2 7 True
Requires Matplotlib.
Step-by-step explanation
- subplots(2, 1, sharex=True) stacks two charts that share the day axis.
- The top chart has two lines — the temperatures and a dashed average — and a legend.
- The printed checks confirm what was drawn: two lines, seven bars and a legend.
Expected output
Running “Two related charts” prints exactly:
Practical applications
- Charts in reports and dashboards.
- Exploring data while analysing it.
Best practices
- Use the fig, ax style.
- Label titles, axes and series.
- Save with an explicit dpi.
Common mistakes
Unlabelled charts
Avoid
Prefer
Without labels, readers can't tell what the chart shows.
show() before savefig()
Avoid
Prefer
Closing the window can clear the figure.
Important notes
- Seaborn and Plotly build on or complement Matplotlib with statistical and interactive charts.
Key takeaways
- Figures contain Axes on which you plot.
- plot, bar and scatter draw common charts.
- Label everything and save with savefig.
Try it yourself
- 1Plot monthly expenses as a bar chart with a horizontal line for the budget.
- 2Create a scatter plot of study hours against marks with axis labels.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
Test yourself across the whole course in the Python practice bank.