Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding matplotlib plots while doing tests with pytest

I am writing a simple library where, given a dataset, it runs a bunch of analyses and shows a lot of plots mid-way. (There are many plt.show() calls)

I have written simple tests to check if different functions run without any error with pytest.

The problem is, once I run pytest, it starts showing all of these plots, and I have to close one by one, it takes a lot of time.

How can I silence all the plots and just see if all the tests passed or not?

like image 318
Zabir Al Nazi Avatar asked Oct 21 '25 17:10

Zabir Al Nazi


1 Answers

If your backend supports interactive display with plt.ion(), then you will need only minimal changes (four lines) to your code:

import matplotlib.pyplot as plt

#define a keyword whether the interactive mode should be turned on
show_kw=True #<--- added
#show_kw=False
    
if show_kw:   #<--- added
    plt.ion() #<--- added
    
#your usual script
plt.plot([1, 2, 3], [4, 5, 6])
plt.show()

plt.plot([1, 3, 7], [4, 6, -1])
plt.show()

plt.plot([1, 3, 7], [4, 6, -1])
plt.show()

#closes all figure windows if show_kw is True
#has no effect if no figure window is open
plt.close("all") #<--- added

print("finished")

However, if the plot generation is time-consuming, this will not be feasible as it only prevents that you have to close them one by one - they will still be generated. In this case, you can switch the backend to a non-GUI version that cannot display the figures:

import matplotlib.pyplot as plt
from matplotlib import get_backend
import warnings

show_kw=True
#show_kw=False

if show_kw:
    curr_backend = get_backend()
    #switch to non-Gui, preventing plots being displayed
    plt.switch_backend("Agg")
    #suppress UserWarning that agg cannot show plots
    warnings.filterwarnings("ignore", "Matplotlib is currently using agg")
    
plt.plot([1, 2, 3], [4, 5, 6])
plt.show()

plt.plot([1, 3, 7], [4, 6, -1])
plt.show()

plt.plot([1, 3, 7], [4, 6, -1])
plt.show()

#display selectively some plots
if show_kw:
    #restore backend
    plt.switch_backend(curr_backend)

plt.plot([1, 2, 3], [-2, 5, -1])
plt.show()

print("finished")
like image 151
Mr. T Avatar answered Oct 23 '25 08:10

Mr. T