INSIGHTS
Software Development

Matplotlib in Python: A Gateway to Visual Storytelling

In this article
  1. Install Matplotlib and choose a working style
  2. Create a labeled line plot
  3. Choose chart type from the comparison
  4. Figure, axes and axis are different things
  5. Validate the dataset before drawing
  6. Save accessible evidence instead of decorative charts
  7. Repeatability and API guidance

Matplotlib helps turn measurements into inspectable figures, but a chart becomes useful only when it has a clear question, named axes, units and a reproducible source. Rather than start with a catalogue of colors and chart types, this tutorial builds one plot, labels it, saves it and checks whether the visual encoding tells the truth about the data.

Install Matplotlib and choose a working style

Use a current Python environment and install Matplotlib in that environment. For scripts intended to be reused, the explicit Figure/Axes style is easier to test than a long sequence of global pyplot state changes. A figure is the overall canvas; each axes object owns its coordinate scales and plotted artists.

python -m pip install matplotlib

If you run on a headless CI server, select a non-interactive backend before importing pyplot and save the chart to a file. For desktop exploration, plt.show() can open an interactive window instead.

Create a labeled line plot

This standalone example uses a small fixed data series so results are reproducible. The explicit ax methods assign what the axes represent, while the title describes the interpretation. The legend is useful because the line has a meaningful label.

import matplotlib
matplotlib.use("Agg")  # for headless scripts
import matplotlib.pyplot as plt

weeks = [1, 2, 3, 4, 5]
requests = [120, 150, 132, 180, 210]
fig, ax = plt.subplots(figsize=(7, 4), layout="constrained")
ax.plot(weeks, requests, marker="o", label="Completed requests")
ax.set_title("Completed service requests by week")
ax.set_xlabel("Week")
ax.set_ylabel("Requests completed")
ax.set_xticks(weeks)
ax.grid(True, axis="y", alpha=0.25)
ax.legend()
fig.savefig("requests_by_week.png", dpi=150)
plt.close(fig)

You should see requests_by_week.png in the working directory. Changing the y-axis to an unrelated percentage or omitting the units would make the same plot misleading.

Choose chart type from the comparison

A line chart emphasizes change in an ordered sequence such as time. A bar chart compares discrete categories; a scatter plot tests relationships between two measured variables. Avoid a pie chart when readers need precise comparison or categories are numerous. Consider a table when exact numeric values are the central task rather than a pattern.

fig, ax = plt.subplots()
ax.bar(["API", "UI", "Batch"], [42, 31, 19])
ax.set_ylabel("Incidents")
ax.set_title("Incident counts by subsystem")
fig.savefig("incidents.png", dpi=150)
plt.close(fig)

Figure, axes and axis are different things

The Figure contains one or more Axes plotting regions. Each axes has x- and y-axis scale objects and coordinate labels. Calling ax.set_xlim changes the visible x range but does not change the underlying data; cropping can conceal a trend, so document any deliberate axis limits.

Validate the dataset before drawing

Check for missing values, inconsistent units, duplicate timestamps and categories with unrecognized labels. An average without a denominator or sample size can mislead. If a metric is a rate, label it as a rate and state the period. Plot one representative sample by hand to detect a parsing error before automating hundreds of charts.

Save accessible evidence instead of decorative charts

Choose a title that states the question, use labels with units, and avoid encoding essential distinctions by color alone. When sharing results in an article, add a text summary or a short data table for readers who cannot interpret the chart image. Do not claim statistical significance from a visual difference without a method that supports it.

Repeatability and API guidance

Wrap chart creation in a function that accepts data, axes and an output path; close generated figures in batch jobs to avoid accumulating memory. The official Matplotlib quick start shows the explicit axes API and recommends that style for reusable applications. Verify the installed version before copying a newer optional layout parameter into an older environment.

Filed under Software Development