Mostly Python

Mostly Python

Share this post

Mostly Python
Mostly Python
Testing a book's code, part 4: Testing Matplotlib data visualizations

Testing a book's code, part 4: Testing Matplotlib data visualizations

MP 80: Modifying files and making assertions about images.

Eric Matthes's avatar
Eric Matthes
Feb 01, 2024
∙ Paid
3

Share this post

Mostly Python
Mostly Python
Testing a book's code, part 4: Testing Matplotlib data visualizations
Share

Note: This is the fourth post in a series about testing. This post, and the ones that follow will only be available to paid subscribers for the first 6 weeks. After that they will be available to everyone. Thank you to everyone who supports my ongoing work on Mostly Python.


In the last post we tested a game built with Pygame, and added a CLI argument to specify any version of Pygame we want. In this post we’ll test the output of data visualization programs that use Matplotlib. In the end, we’ll be able to run tests against any version of Matplotlib as well.

Testing data visualization programs is interesting, because there’s a variety of output. There’s some terminal output that’s fairly straightforward to make assertions about, but the graphical output is much more interesting to test. Let’s dig in.

Testing one Matplotlib program

Here’s the first program we want to test, called mpl_squares.py:

import matplotlib.pyplot as plt

input_values = [1, 2, 3, 4, 5]
squares = [1, 4, 9, 16, 25]

plt.style.use('seaborn-v0_8')
fig, ax = plt.subplots()
ax.plot(input_values, squares, linewidth=3)

# Set chart title and label axes.
...

plt.show()

This code defines a small dataset, and then generates a line graph:

A simple plot as seen in Matplotlib’s plot viewer. The viewer is great for interactive work, but not very compatible with automated testing.

The call to plt.show() causes Matplotlib’s plot viewer to appear. This is great for introducing people to plotting libraries, but it’s problematic in an automated test environment. We don’t really want to call plt.show() in a test run.

Rewriting the file before testing it

We won’t test this file directly because we don’t want to call plt.show(), and we can’t change the files in the book’s repository. However, we can copy them to a different directory outside the repository and then do whatever we want with them. So let’s modify the program to write the plot as an image file. We can then make assertions about the freshly-generated image file.

We’ll start by making a new test file, called test_matplotlib_programs.py. Here’s the first part of the test for mpl_squares.py:

Keep reading with a 7-day free trial

Subscribe to Mostly Python to keep reading this post and get 7 days of free access to the full post archives.

Already a paid subscriber? Sign in
© 2025 Eric Matthes
Privacy ∙ Terms ∙ Collection notice
Start writingGet the app
Substack is the home for great culture

Share