Data Visualization with Matplotlib

Published by Brayan K

Matplotlib is Python's most established plotting library. With a handful of pyplot calls you can turn raw numbers into line charts, scatter plots, bar charts, and histograms — and the object-oriented API gives you full control over every figure and axes.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Build a figure whose data and labels you can inspect

A plotting call can succeed while drawing a misleading report. We will build a small shop report, keep a handle to every axes, check the values stored in its artists, and export a real image. The goal is a chart with a stated meaning, not a collection of decorative styles.

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

days = [1, 2, 3]
orders = [8, 11, 9]
fig, ax = plt.subplots(figsize=(6, 3.5), constrained_layout=True)
line, = ax.plot(days, orders, marker="o", label="Completed orders")
ax.set(title="Orders across three days", xlabel="Day", ylabel="Orders")
ax.set_xticks(days)
ax.legend()
print(line.get_xdata().tolist())
print(line.get_ydata().tolist())
print(ax.get_xlabel(), ax.get_ylabel())
print([text.get_text() for text in ax.get_legend().get_texts()])

# ✅ Expected output:
# [1, 2, 3]
# [8, 11, 9]
# Day Orders
# ['Completed orders']
The chart this code draws: Keep the Figure, Axes and plotted line as separate objectsOpen full-size image
What this code draws, rendered with Matplotlib.

The Figure is the whole image; an Axes is a plotting area inside it; a Line2D artist holds this series. Keep these returned objects so a later operation targets the intended plot. The Figure & Axes owns the detailed object hierarchy.

Every example selects the noninteractive Agg backend before importing pyplot. The lesson shows saved chart previews; after you press Run, the browser editor shows your printed checks and static previews of the figures your code creates. Edit the data and run again to see the changed chart, or download its PNG. This does not play animations or open a desktop window. On a local desktop, choose an available interactive backend and call plt.show() if you want a window. Native checks use Matplotlib 3.11.1; examples are also exercised in the browser’s bundled version.

The x and y values must describe the same observations

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(6, 3.5), constrained_layout=True)
try:
    ax.plot([1, 2, 3], [8, 11])
except ValueError as problem:
    print(str(problem))
line, = ax.plot([1, 2, 3], [8, 11, 9], marker="o")
ax.set(title="Three paired observations", xlabel="Day", ylabel="Orders")
ax.set_xticks([1, 2, 3])
print(len(line.get_xdata()) == len(line.get_ydata()))

# ✅ Expected output:
# x and y must have same first dimension, but have shapes (3,) and (2,)
# True
The chart this code draws: Catch a missing observation before showing the corrected seriesOpen full-size image
What this code draws, rendered with Matplotlib.

The actual error tells you the two input shapes. Do not truncate one list merely to silence it: determine which observation is absent. Also preserve pairing when sorting. Sorting x alone changes which y belongs to each observation. A line joins points in their supplied order; it does not infer chronological order.

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

observations = [(3, 9), (1, 8), (2, 11)]
ordered = sorted(observations)
days, orders = zip(*ordered)
fig, ax = plt.subplots(figsize=(6, 3.5), constrained_layout=True)
line, = ax.plot(days, orders, marker="o")
ax.set(title="Observations ordered by day", xlabel="Day", ylabel="Orders")
ax.set_xticks(days)
print(list(zip(line.get_xdata().tolist(), line.get_ydata().tolist())))

# ✅ Expected output:
# [(1, 8), (2, 11), (3, 9)]
The chart this code draws: Sort pairs together before drawing a time-ordered lineOpen full-size image
What this code draws, rendered with Matplotlib.

Sorting by the pair’s first item is suitable because each day here is unique. Duplicate timestamps, missing days and aggregation rules need an explicit data policy before plotting. A chart library cannot decide those rules for you.

Choose the mark that matches the question

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(6, 3.5), constrained_layout=True)
bars = ax.bar(["North", "South"], [28, 35], color=["#2563eb", "#0f766e"])
ax.set(title="Completed orders by shop", xlabel="Shop", ylabel="Orders")
ax.set_ylim(bottom=0)
print([int(bar.get_height()) for bar in bars])
print(float(ax.get_ylim()[0]))
fig.canvas.draw()
print([label.get_text() for label in ax.get_xticklabels()])

# ✅ Expected output:
# [28, 35]
# 0.0
# ['North', 'South']
The chart this code draws: Use bar height for comparable category totalsOpen full-size image
What this code draws, rendered with Matplotlib.

Bars compare amounts by length, so a zero baseline preserves that visual comparison for these nonnegative counts. A connected line between unrelated shop categories would suggest an ordering or continuity we did not measure. Color supplements the labels; it should not be the only way to identify a shop.

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(6, 3.5), constrained_layout=True)
points = ax.scatter([2, 4, 5], [7, 8, 10], color="#7c3aed")
ax.set(title="Practice sessions and completed tasks", xlabel="Sessions", ylabel="Tasks")
print(points.get_offsets().tolist())
print(len(ax.lines))

# ✅ Expected output:
# [[2.0, 7.0], [4.0, 8.0], [5.0, 10.0]]
# 0
The chart this code draws: Show paired measurements without inventing connecting segmentsOpen full-size image
What this code draws, rendered with Matplotlib.

A scatter plot shows paired observations. A visible relationship does not establish that practice caused the task count: group selection, measurement and other factors can matter. Plotting is not a substitute for study design.

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

durations = [1, 2, 2, 3, 5, 5]
fig, ax = plt.subplots(figsize=(6, 3.5), constrained_layout=True)
counts, edges, patches = ax.hist(durations, bins=[0.0, 2.0, 4.0, 6.0], edgecolor="white")
ax.set(title="Task durations", xlabel="Minutes", ylabel="Tasks")
print(counts.tolist())
print(edges.tolist())
print(int(counts.sum()))

# ✅ Expected output:
# [1.0, 3.0, 2.0]
# [0.0, 2.0, 4.0, 6.0]
# 6
The chart this code draws: Inspect the bin edges and counts of a distributionOpen full-size image
What this code draws, rendered with Matplotlib.

A histogram groups numerical observations into intervals. These bins include their left edge and exclude the right, except the final bin includes its right edge. The chosen edges affect the picture; keep them comparable when comparing groups. Histograms owns bin-selection and density details.

Target each axes explicitly in a multi-panel report

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

fig, axes = plt.subplots(1, 2, figsize=(8, 3.5), constrained_layout=True)
axes[0].plot([1, 2, 3], [8, 11, 9], marker="o")
axes[0].set(title="North: daily orders", xlabel="Day", ylabel="Orders")
axes[0].set_xticks([1, 2, 3])
axes[1].bar(["North", "South"], [28, 35], color="#0f766e")
axes[1].set(title="Shop totals", xlabel="Shop", ylabel="Orders")
axes[1].set_ylim(bottom=0)
print([ax.get_title() for ax in axes])
print(len(fig.axes))
print(len(axes[0].lines), len(axes[1].containers))

# ✅ Expected output:
# ['North: daily orders', 'Shop totals']
# 2
# 1 1
The chart this code draws: Keep titles and units attached to the intended subplotOpen full-size image
What this code draws, rendered with Matplotlib.

The return shape changes with the subplot arrangement: one subplot normally gives one Axes; this row gives a one-dimensional array. If code must always use a two-dimensional axes array, pass squeeze=False. Avoid relying on pyplot’s current axes inside a reusable report function.

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(6, 3.5), constrained_layout=True)
ax.plot([1, 2, 3], [8, 11, 9], marker="o", label="North")
ax.plot([1, 2, 3], [10, 12, 13], marker="s", linestyle="--", label="South")
ax.set(title="Orders by day and shop", xlabel="Day", ylabel="Orders")
ax.set_xticks([1, 2, 3])
print(ax.get_legend() is None)
legend = ax.legend()
print([label.get_text() for label in legend.get_texts()])

# ✅ Expected output:
# True
# ['North', 'South']
The chart this code draws: A label does not display itself until a legend is requestedOpen full-size image
What this code draws, rendered with Matplotlib.

Different markers and line styles remain useful when color is difficult to distinguish. Use clear units and a descriptive title instead of expecting a legend to explain the whole chart. Labels, Titles & Legends owns detailed annotation choices.

Export the figure you mean, then manage its lifetime

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

from io import BytesIO

fig, ax = plt.subplots(figsize=(6, 3.5), constrained_layout=True)
ax.bar(["Reviewed", "Pending"], [12, 4], color=["#0f766e", "#64748b"])
ax.set(title="Lesson review queue", xlabel="Status", ylabel="Lessons")
image = BytesIO()
fig.savefig(image, format="png", dpi=100)
print(image.getvalue().startswith(b"\x89PNG\r\n\x1a\n"))
print(len(ax.containers[0]))

# ✅ Expected output:
# True
# 2
The chart this code draws: Save an actual PNG to memory and check its file signatureOpen full-size image
What this code draws, rendered with Matplotlib.

The file format is explicit because a BytesIO object has no filename extension. The signature check confirms that image encoding happened; the artist checks confirm the data. Neither alone proves that every label is readable, so inspect the rendered preview too. Saving Figures owns export formats, DPI and bounding-box options.

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
number = fig.number
print(plt.fignum_exists(number))
plt.close(fig)
print(plt.fignum_exists(number))

# ✅ Expected output:
# True
# False

pyplot retains references to open figures. In a long batch, save each report and close that figure when finished. The other examples leave their figure open so the lesson’s preview renderer can capture it. Closing does not delete an already saved image; a later pyplot save without the intended figure can target a different or empty figure.

Complete a labeled category chart

Draw the provided counts with bars, give the vertical axis its unit, and inspect the actual artist heights. The hints name the plotting and labeling methods.

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(6, 3.5), constrained_layout=True)
bars = ax.___(["Pass", "Retry"], [7, 2])
ax.___("Learners")
ax.set_title("Practice outcomes")
ax.set_xlabel("Outcome")
ax.set_ylim(bottom=0)
print([int(bar.get_height()) for bar in bars])
print(ax.get_ylabel())

# 👉 replace ___ with bar
# 👉 replace ___ with set_ylabel

# ✅ Expected output:
# [7, 2]
# Learners

Create a two-panel report and verify its contents

Use daily orders [8, 11, 9] for days [1, 2, 3] and shop totals North=28, South=35. Build a line panel and a bar panel, each with a title and both axis labels. Export the whole figure to PNG in memory. Print the plotted values, the number of axes and a check of the PNG signature. Keep the source data paired and the bar baseline at zero.

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

from io import BytesIO

days, orders = [1, 2, 3], [8, 11, 9]
fig, axes = plt.subplots(1, 2, figsize=(8, 3.5), constrained_layout=True)
line, = axes[0].plot(days, orders, marker="o", color="#2563eb")
axes[0].set(title="North: daily orders", xlabel="Day", ylabel="Orders")
axes[0].set_xticks(days)
bars = axes[1].bar(["North", "South"], [28, 35], color="#0f766e")
axes[1].set(title="Shop totals", xlabel="Shop", ylabel="Orders")
axes[1].set_ylim(bottom=0)
image = BytesIO()
fig.savefig(image, format="png", dpi=100)
print(line.get_ydata().tolist())
print([int(bar.get_height()) for bar in bars])
print(len(fig.axes))
print(image.getvalue().startswith(b"\x89PNG\r\n\x1a\n"))

# ✅ Expected output:
# [8, 11, 9]
# [28, 35]
# 2
# True
The chart this code draws: Verify the figure before sharing the reportOpen full-size image
What this code draws, rendered with Matplotlib.

Inspect the saved preview at its intended display size. If the labels collide, change the figure size or layout and render it again; a passing numerical check cannot certify visual readability.

Practice quiz

What does ax refer to in fig, ax = plt.subplots()?

  • One plotting area inside the figure
  • The image file
  • A list of every chart style
  • The x-axis alone

Answer: One plotting area inside the figure. An Axes contains the plotted artists, axes, ticks and labels.

Why sort (day, count) pairs together?

  • To change counts to strings
  • To preserve which count belongs to each day
  • To guarantee causation
  • To remove duplicate days automatically

Answer: To preserve which count belongs to each day. Sorting one coordinate list alone destroys the observation pairing.

Which plot directly compares totals for unrelated named shops?

  • Histogram
  • Connected time-series line
  • Bar chart
  • Contour plot

Answer: Bar chart. Bars compare category amounts; a line can imply continuity.

What does label="North" do before ax.legend() is called?

  • Creates a separate image
  • Changes the axis units
  • Always shows a visible legend
  • Stores the artist label for a later legend

Answer: Stores the artist label for a later legend. Request a legend explicitly to display eligible labels.

What does this program print? import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt fig, axes = plt.subplots(1, 2) print(len(fig.axes)) plt.close(fig)

  • 2
  • 1
  • 0
  • 4

Answer: 2. Two subplots create two Axes objects in the Figure.

What does this program print? import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt fig, ax = plt.subplots() bars = ax.bar(["A", "B"], [3, 5]) print([int(bar.get_height()) for bar in bars]) plt.close(fig)

  • [0, 1]
  • [3, 5]
  • [5, 3]
  • [8]

Answer: [3, 5]. The rectangle heights retain the supplied category values.

What does a PNG signature check prove?

  • The data is unbiased
  • Every label is legible
  • PNG encoding produced the expected file signature
  • The chart proves a causal claim

Answer: PNG encoding produced the expected file signature. Inspect the data and visual rendering separately.

When a saved report is no longer needed in a long pyplot batch, what releases its registered figure?

  • ax.legend()
  • fig.savefig()
  • ax.set_title()
  • plt.close(fig)

Answer: plt.close(fig). Saving does not itself close the figure.

Continue this course

Related lessons