Skip to content

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.

Beginner 10 min read·Lesson 241 of 306 in Python Programming

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

Python
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [2, 4, 1], label="sales")
ax.set_title("Sales")
ax.legend()
fig.savefig("sales.png")
  • fig, ax = plt.subplots().
  • Always label charts.
  • savefig writes an image.

Code examples

A simple line chart

Python
import matplotlib.pyplot as plt
months = ["Jan", "Feb", "Mar", "Apr"]
visitors = [320, 410, 380, 520]
fig, ax = plt.subplots()
ax.plot(months, visitors, marker="o")
ax.set_title("Website visitors")
ax.set_ylabel("Visitors")
plt.show()

Requires Matplotlib. plt.show() opens a window with the chart.

A bar chart saved to a file

Python
import os
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
months = ["Jan", "Feb", "Mar", "Apr"]
sales = [120, 150, 90, 180]
fig, ax = plt.subplots(figsize=(6, 4))
ax.bar(months, sales, color="#e07a5f")
ax.set_title("Monthly sales")
ax.set_ylabel("Units")
fig.savefig("sales.png", dpi=100)
print(os.path.getsize("sales.png") > 0, ax.get_title(), len(ax.patches))
Output
True Monthly sales 4

Requires Matplotlib. The Agg backend draws without opening a window.

More examples

Two related charts

Python
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
days = list(range(1, 8))
temps = [31, 33, 32, 35, 36, 34, 30]
rain = [0, 2, 5, 0, 0, 12, 20]
fig, (top, bottom) = plt.subplots(2, 1, sharex=True, figsize=(6, 5))
top.plot(days, temps, marker="o", label="Max temp (C)")
top.axhline(sum(temps) / len(temps), linestyle="--", label="Average")
top.legend()
bottom.bar(days, rain, label="Rain (mm)")
bottom.set_xlabel("Day")
fig.tight_layout()
fig.savefig("weather.png")
print(len(top.lines), len(bottom.patches), top.get_legend() is not None)
Output
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:

TextOutput
2 7 True

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

ax.plot(x, y)

Prefer

ax.plot(x, y, label="revenue")
ax.set_xlabel("month")
ax.set_ylabel("₹ lakh")
ax.legend()

Without labels, readers can't tell what the chart shows.

show() before savefig()

Avoid

plt.show()
fig.savefig("out.png") # may save a blank image

Prefer

fig.savefig("out.png")
plt.show()

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

  1. 1
    Plot monthly expenses as a bar chart with a horizontal line for the budget.
  2. 2
    Create 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.