Skip to main content

Data analysis · Beginner · 20 min

Plot data with matplotlib's figure and axes interface

By Padding · Updated 18 Nov 2026
Python 3.15 · matplotlib 3.11.2 · NumPy 2.5.5 (checked on python:3.15-slim)

You will draw line, bar, scatter and histogram charts with matplotlib's figure and axes interface, format their ticks as thousands, percentages and dates, annotate the busiest day, combine all four in one grid and save it as SVG and as a sharp 2x PNG.

On this page

matplotlib has two ways to draw. The short way calls functions on plt directly (plt.plot, plt.title) and lets matplotlib decide which chart they land on. The explicit way creates a Figure (the whole image) and one or more Axes (each plotting area) with fig, ax = plt.subplots(), then calls methods on the object you mean. The explicit way is what you want once a script has more than one chart, and matplotlib's own documentation recommends it for anything beyond a quick look, so this tutorial uses it throughout.

You build a small project for a made-up online shop with six months of orders: a line chart of revenue per day, a bar chart of orders by sales channel, a scatter plot of delivery time against distance and a histogram of order values. Each chart gets a title, axis labels with units and tick labels people can read without counting zeros. Then you put all four in one grid, point out the busiest day, and save the result as an SVG for the web and a PNG at twice the pixel density for slides and messaging apps.

The data is generated with a fixed seed, so your numbers match the ones printed here. Everything runs in a terminal with no screen attached, which is how charts get made on servers, in scheduled jobs and in CI.

Step 1 · Create the project and install matplotlib

Make a throwaway folder, a virtual environment inside it and a charts/ folder for the output. Then install matplotlib with NumPy, pinned to the versions this tutorial was written against:

Bash
mkdir -p ~/matplotlib-demo/charts
cd ~/matplotlib-demo
python3 -m venv .venv
. .venv/bin/activate
pip install "matplotlib==3.11.2" "numpy==2.5.5"
python -c "import matplotlib, numpy; print(matplotlib.__version__, numpy.__version__)"

matplotlib pulls in a few small dependencies of its own (Pillow for PNG files, fontTools, kiwisolver and others). The wheels come to roughly 30 MB in total. If you are on prepaid mobile data, run the install once on Wi-Fi: pip keeps a cache, so a later install of the same versions in another project downloads nothing.

Check it worked

The last command prints 3.11.2 2.5.5. Your prompt starts with (.venv), which tells you the environment is active. If you open a new terminal later, run cd ~/matplotlib-demo and . .venv/bin/activate again before the next step.

Step 2 · Generate the sample data

Real data has gaps and surprises that would distract from the charts, so this step generates six months of clean, believable numbers in data.py. Every chart script imports it. The seed makes numpy.random.default_rng return the same numbers on every run and every machine.

Bash
cd ~/matplotlib-demo
. .venv/bin/activate
cat > data.py <<'PY'
"""Six months of made-up orders for a small online shop. Same numbers on every run."""
import numpy as np

rng = np.random.default_rng(seed=2026)

DAYS = np.arange(np.datetime64("2026-01-01"), np.datetime64("2026-07-01"))
weekday = (DAYS.astype("int64") + 3) % 7  # 0 is Monday
weekend = weekday >= 5

trend = np.linspace(90, 150, DAYS.size)
orders = rng.poisson(trend * np.where(weekend, 1.3, 1.0))
PROMO_DAY = np.datetime64("2026-03-27")
orders[DAYS == PROMO_DAY] += 260

revenue = (orders * rng.normal(8_500, 500, DAYS.size)).round(-2)  # NGN per day

CHANNELS = ["WhatsApp", "Website", "Instagram", "Walk-in"]
channel_orders = rng.multinomial(orders.sum(), [0.44, 0.28, 0.18, 0.10])

distance_km = rng.uniform(1, 25, 200).round(1)
delivery_min = (20 + 3.2 * distance_km + rng.normal(0, 8, 200)).round()

order_value = rng.lognormal(np.log(8_000), 0.5, 2_000).round(-1)  # NGN per order
PY
cat > check_data.py <<'PY'
import data

print("days:", data.DAYS.size, "from", data.DAYS[0], "to", data.DAYS[-1])
print("orders:", f"{data.orders.sum():,}", "busiest day:", data.DAYS[data.orders.argmax()])
for name, n in zip(data.CHANNELS, data.channel_orders):
    print(f"{name:<10}{n:>7,}  {n / data.channel_orders.sum():.1%}")
print("deliveries:", data.distance_km.size, "order values:", data.order_value.size)
PY
python check_data.py

The shop sells in Nigerian naira (NGN), takes most orders on WhatsApp, gets busier at weekends and ran a promotion on 27 March. Days are NumPy datetime64 values, which matplotlib plots as dates without any conversion.

Check it worked

The script prints:

Text
days: 181 from 2026-01-01 to 2026-06-30
orders: 23,907 busiest day: 2026-03-27
WhatsApp   10,474  43.8%
Website     6,689  28.0%
Instagram   4,359  18.2%
Walk-in     2,385  10.0%
deliveries: 200 order values: 2000

Step 3 · Draw a first chart with a figure and an axes

plt.subplots() returns two objects. fig is the Figure: the canvas, its size and everything you save. ax is an Axes: one plotting area with its own x-axis, y-axis, title and data. You draw by calling methods on ax and save by calling a method on fig.

A figure drawn as a grey frame with an overall title, holding two dashed boxes: a line chart of revenue and a bar chart of channel shares. Labels point to the figure, to one axes, and to the methods that set the axes title, the x label and the tick labels
One Figure holds every Axes; each Axes has its own title, labels and ticks

Two lines at the top of the script matter on any machine without a screen. matplotlib.use("Agg") picks the Agg backend, which renders to files only and never tries to open a window. Call it before importing pyplot. On a server matplotlib usually falls back to Agg anyway, but saying so makes the script behave the same on your laptop, a server and a scheduled job. The svg.fonttype setting writes SVG text as real text instead of drawn outlines, so titles stay searchable and selectable and screen readers can read them.

Bash
cd ~/matplotlib-demo
. .venv/bin/activate
cat > first_chart.py <<'PY'
import matplotlib

matplotlib.use("Agg")  # draw to files only; no window

import matplotlib.pyplot as plt  # noqa: E402

import data  # noqa: E402

plt.rcParams["svg.fonttype"] = "none"  # keep text as text in SVG files

fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(data.DAYS, data.orders, color="#2a2d33", linewidth=1)
ax.set_title("Orders per day, January to June 2026")
ax.set_xlabel("Date")
ax.set_ylabel("Orders per day")

fig.savefig("charts/orders-per-day.svg")
print(type(fig).__name__, type(ax).__name__, "axes on figure:", len(fig.axes))
print("saved charts/orders-per-day.svg")
PY
python first_chart.py

figsize is in inches, width first. The x-axis labels come out cramped and the dates use matplotlib's default style; the next step fixes both.

Check it worked

The script prints Figure Axes axes on figure: 1 and saved charts/orders-per-day.svg, and no window opens. Open charts/orders-per-day.svg in a browser: a dark line with a tall spike in late March, the title above it, and you can select the title text with the mouse.

Step 4 · Make the tick labels readable

Default tick labels are correct but hard to read. Revenue of 1,500,000 shows as 1.5 with a 1e6 multiplier in the corner, and percentages show as fractions. matplotlib separates where ticks go (a locator) from how they are written (a formatter), and every axis has one of each.

Put each chart in its own function that takes an ax and draws on it. That is the habit that pays off in the grid step: the same function can draw a single chart or one panel of four. Create plots.py:

Bash
cd ~/matplotlib-demo
. .venv/bin/activate
cat > plots.py <<'PY'
"""Chart functions. Each one draws on the Axes it is given."""
import matplotlib

matplotlib.use("Agg")

import matplotlib.dates as mdates  # noqa: E402
import matplotlib.pyplot as plt  # noqa: E402
from matplotlib.ticker import MultipleLocator, PercentFormatter, StrMethodFormatter  # noqa: E402

import data  # noqa: E402

plt.rcParams.update({
    "svg.fonttype": "none",
    "font.size": 9,
    "axes.spines.top": False,
    "axes.spines.right": False,
})

INK = "#2a2d33"
THOUSANDS = StrMethodFormatter("{x:,.0f}")  # 1500000 -> 1,500,000


def draw_revenue(ax):
    ax.plot(data.DAYS, data.revenue, color=INK, linewidth=1)
    ax.set_title("Revenue per day", loc="left")
    ax.set_ylabel("Revenue (NGN)")
    ax.yaxis.set_major_formatter(THOUSANDS)
    locator = mdates.AutoDateLocator()
    ax.xaxis.set_major_locator(locator)
    ax.xaxis.set_major_formatter(mdates.ConciseDateFormatter(locator))
    ax.set_ylim(bottom=0)
    ax.margins(x=0)


def draw_channels(ax):
    shares = data.channel_orders / data.channel_orders.sum()
    order = shares.argsort()  # smallest first, so the largest bar ends up on top
    names = [data.CHANNELS[i] for i in order]
    ax.barh(names, shares[order], color=INK)
    ax.set_title("Share of orders by channel", loc="left")
    ax.set_xlabel("Share of all orders, January to June")
    ax.xaxis.set_major_formatter(PercentFormatter(xmax=1, decimals=0))
    ax.set_xlim(0, 0.5)
PY
cat > tick_formats.py <<'PY'
import plots  # first: sets the Agg backend and the shared style

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(8, 4))
plots.draw_revenue(ax)
fig.savefig("charts/revenue.svg", bbox_inches="tight")
print("y ticks:", [t.get_text() for t in ax.get_yticklabels()])
print("x ticks:", [t.get_text() for t in ax.get_xticklabels()])

fig, ax = plt.subplots(figsize=(6, 3))
plots.draw_channels(ax)
fig.savefig("charts/channels.svg", bbox_inches="tight")
print("x ticks:", [t.get_text() for t in ax.get_xticklabels()])
PY
python tick_formats.py

What each formatter does:

  • Thousands: StrMethodFormatter("{x:,.0f}") applies a Python format string to every tick value. The comma adds thousands separators and .0f drops decimals. For a narrow chart you could write millions instead, for example with FuncFormatter(lambda v, _: f"{v / 1e6:.1f}M").
  • Percentages: PercentFormatter(xmax=1) reads the data as fractions (0.44) and writes them as percentages (44%). Use xmax=100 if your data is already in percent.
  • Dates: ConciseDateFormatter writes the year once, at the first tick, and only month names after it, instead of repeating 2026-02 on every tick. It needs the same locator the axis uses, which is why the code creates the AutoDateLocator first.

loc="left" aligns titles with the left edge of the plot, where people start reading. bbox_inches="tight" crops the saved file to what is drawn, so long tick labels are never cut off.

Tick labels are only worked out when the figure is drawn, which is why the script reads them after savefig. Before that, get_yticklabels() returns empty strings.

Check it worked

The script prints three lines of tick labels: revenue from '0' to '4,000,000' in steps of 500,000; dates as '2026', 'Feb', 'Mar', 'Apr', 'May', 'Jun'; and channel shares from '0%' to '50%'. Open charts/channels.svg: four bars, WhatsApp at the top and longest, ending a little past the 40% tick.

Step 5 · Add a scatter plot and a histogram

The other two chart types answer different questions. A scatter plot shows whether two measures move together: does a longer delivery take longer? A histogram shows how one measure is spread out: are most orders small, with a few large ones?

Append both functions to plots.py. Appending keeps the file you already checked intact:

Bash
cd ~/matplotlib-demo
. .venv/bin/activate
cat >> plots.py <<'PY'


def draw_deliveries(ax):
    ax.scatter(data.distance_km, data.delivery_min, s=12, color=INK, alpha=0.6, linewidths=0)
    ax.set_title("Delivery time against distance", loc="left")
    ax.set_xlabel("Distance (km)")
    ax.set_ylabel("Delivery time (minutes)")
    ax.set_xlim(0, 26)
    ax.set_ylim(bottom=0)


def draw_order_values(ax):
    ax.hist(data.order_value, bins=range(0, 40_001, 2_000), color=INK, edgecolor="white")
    ax.set_title("Order values", loc="left")
    ax.set_xlabel("Order value (NGN)")
    ax.set_ylabel("Number of orders")
    ax.xaxis.set_major_locator(MultipleLocator(10_000))
    ax.xaxis.set_major_formatter(THOUSANDS)
PY
cat > more_charts.py <<'PY'
import plots  # first: sets the Agg backend and the shared style

import matplotlib.pyplot as plt

import data

fig, ax = plt.subplots(figsize=(6, 4))
plots.draw_deliveries(ax)
fig.savefig("charts/deliveries.svg", bbox_inches="tight")

fig, ax = plt.subplots(figsize=(6, 4))
plots.draw_order_values(ax)
fig.savefig("charts/order-values.svg", bbox_inches="tight")

print("scatter points:", data.distance_km.size, "histogram bars:", len(ax.patches))
print("orders above NGN 40,000 (off the chart):", int((data.order_value > 40_000).sum()))
PY
python more_charts.py

Three choices worth copying:

  • Bin edges you chose. bins=range(0, 40_001, 2_000) gives bars exactly NGN 2,000 wide starting at zero, so a reader can say "most orders are between 4,000 and 10,000". With bins=20 matplotlib picks odd edges such as 1,734.5. Fixed edges also leave out the rare huge order; the script counts how many fell off the end so you can mention it.
  • Transparent points. alpha=0.6 lets overlapping points show as darker spots, so you can see where deliveries cluster.
  • Fewer, rounder ticks. MultipleLocator(10_000) puts a tick every 10,000. Without it the formatted labels (5,000, 10,000, ...) run into each other.

Check it worked

The script prints scatter points: 200 histogram bars: 20 and orders above NGN 40,000 (off the chart): 1. Open charts/deliveries.svg: points rise from bottom left to top right. Open charts/order-values.svg: a hump between 4,000 and 10,000 with a long tail to the right, and x ticks at 0, 10,000, 20,000, 30,000 and 40,000.

Step 6 · Point out the busiest day with an annotation

A spike with no explanation makes readers guess. ax.annotate draws text with an optional arrow to a data point. xy is the point, in data coordinates (here a date and an amount). xytext is where the text goes; with textcoords="offset points" it is an offset from the point in points (1/72 inch), so the label keeps its distance from the spike whatever the axis range.

Append a function that finds the highest revenue day and labels it:

Bash
cd ~/matplotlib-demo
. .venv/bin/activate
cat >> plots.py <<'PY'


def annotate_peak(ax):
    """Point at the busiest day on a chart drawn by draw_revenue."""
    i = data.revenue.argmax()
    day = data.DAYS[i].astype(object)  # a datetime.date, for the label
    ax.annotate(
        f"Promo day, {day:%d %b}\nNGN {data.revenue[i]:,.0f}",
        xy=(data.DAYS[i], data.revenue[i]),
        xytext=(12, -12),
        textcoords="offset points",
        va="top",
        arrowprops={"arrowstyle": "->", "color": INK},
    )
    return day, data.revenue[i]
PY
cat > annotate.py <<'PY'
import plots  # first: sets the Agg backend and the shared style

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(8, 4))
plots.draw_revenue(ax)
day, value = plots.annotate_peak(ax)
fig.savefig("charts/revenue-annotated.svg", bbox_inches="tight")
print(f"annotated {day:%Y-%m-%d} at NGN {value:,.0f}")
PY
python annotate.py

The label is computed from the data, not typed in. If next month's data has a bigger day, the arrow moves to it and the text changes with it.

Check it worked

The script prints annotated 2026-03-27 at NGN 3,429,400. Open charts/revenue-annotated.svg: an arrow points at the tip of the March spike, with "Promo day, 27 Mar" and the amount on two lines to its right, clear of the line.

Step 7 · Arrange the four charts in a grid

plt.subplots(2, 2) returns a figure and a 2 by 2 array of Axes. axs[0, 0] is the top left, axs[1, 1] the bottom right. Because each chart is a function that takes an Axes, filling the grid is four calls.

layout="constrained" asks matplotlib to size and space the panels so titles, tick labels and axis labels never overlap. It does the same job as calling fig.tight_layout() before saving, and it also makes room for a figure title. Use one of the two in every multi-panel figure; without either, labels of neighbouring panels often collide.

Bash
cd ~/matplotlib-demo
. .venv/bin/activate
cat > dashboard.py <<'PY'
import plots  # first: sets the Agg backend and the shared style

import matplotlib.pyplot as plt


def build():
    fig, axs = plt.subplots(2, 2, figsize=(10, 7), layout="constrained")
    plots.draw_revenue(axs[0, 0])
    plots.annotate_peak(axs[0, 0])
    plots.draw_channels(axs[0, 1])
    plots.draw_deliveries(axs[1, 0])
    plots.draw_order_values(axs[1, 1])
    fig.suptitle("Shop orders, January to June 2026", x=0.01, ha="left",
                 fontsize=12, fontweight="bold")
    return fig


if __name__ == "__main__":
    fig = build()
    fig.savefig("charts/dashboard.svg")
    print("axes:", len(fig.axes), "titles:", [ax.get_title(loc="left") for ax in fig.axes])
PY
python dashboard.py

build() returns the figure instead of saving it, so the next step can import it and save it in other formats without drawing everything twice in code. If your panels share an axis (four regions over the same dates, say), pass sharex=True or sharey=True to plt.subplots so they line up and repeated tick labels are hidden.

Check it worked

The script prints axes: 4 titles: followed by the four chart titles in reading order. Open charts/dashboard.svg: the bold title at the top left, revenue with its annotation top left, channel bars top right, the scatter bottom left and the histogram bottom right, with no text overlapping.

Step 8 · Save an SVG and a sharp 2x PNG

Choose the format by where the chart goes. SVG is vector: it stays sharp at any zoom and suits web pages. PNG is pixels: it works everywhere, including slide software, documents and chat apps that do not show SVG.

A PNG's size in pixels is the figure size in inches times dpi (dots per inch). This figure is 10 by 7 inches, so dpi=100 gives 1000 by 700 pixels. Phones and most laptops now have screens with two or more device pixels per CSS pixel, and a 1000-pixel image shown 1000 CSS pixels wide looks soft on them. Save a second copy at dpi=200 and show it at the same size: that is a 2x image.

A 10 by 7 inch figure saved twice: at dpi 100 it becomes a 1000 by 700 pixel PNG, at dpi 200 a 2000 by 1400 pixel PNG that is shown at 1000 by 700 with two device pixels per CSS pixel
Pixel size is figure size in inches times dpi
Bash
cd ~/matplotlib-demo
. .venv/bin/activate
cat > export.py <<'PY'
from pathlib import Path

import matplotlib

from dashboard import build

fig = build()
width, height = fig.get_size_inches()
print("backend:", matplotlib.get_backend())
print(f"figure: {width:g} x {height:g} inches")

fig.savefig("charts/dashboard.svg")
fig.savefig("charts/dashboard.png", dpi=100)
fig.savefig("charts/dashboard@2x.png", dpi=200)

for name in ("dashboard.svg", "dashboard.png", "dashboard@2x.png"):
    path = Path("charts", name)
    print(f"{name:<18}{path.stat().st_size / 1024:>7.0f} KB")
PY
cat > check_png.py <<'PY'
"""Print the pixel size of each PNG named on the command line, read from its header."""
import struct
import sys

for name in sys.argv[1:]:
    with open(name, "rb") as f:
        head = f.read(24)
    if head[:8] != b"\x89PNG\r\n\x1a\n":
        print(name, "is not a PNG")
        continue
    width, height = struct.unpack(">II", head[16:24])
    print(f"{name}: {width} x {height} px")
PY
python export.py
python check_png.py charts/dashboard.png charts/dashboard@2x.png

check_png.py reads the width and height straight from the PNG header, so it needs no image library. The export does not use bbox_inches="tight": constrained layout has already fitted everything inside the figure, and leaving the crop off keeps the pixel size exact, which matters when a slide template or web page expects a fixed size.

On a page, show the 2x file at half its pixel width, for example <img src="dashboard@2x.png" width="1000" height="700" alt="...">, and write alt text that states what the chart shows, not just its title. If many of your readers are on low-end Android phones and prepaid data, compare the file sizes the script prints: the SVG is usually the smallest of the three and still sharp, so prefer it on the web and keep the 2x PNG for places that need a bitmap.

Check it worked

export.py prints backend: Agg, figure: 10 x 7 inches and three file sizes, something like 65 KB for the SVG, 90 KB for the PNG and 210 KB for the 2x PNG; yours may differ slightly. check_png.py prints charts/dashboard.png: 1000 x 700 px and charts/dashboard@2x.png: 2000 x 1400 px. Open both PNGs side by side at the same display size and zoom in: the 2x copy has crisp text where the 1x copy blurs.

When you are done, delete the project with rm -rf ~/matplotlib-demo.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.