Stephen Strosko
Stephen Strosko

Reputation: 665

How to close testing figures matplotlib

I have a series of image comparison tests in a module that I have made. When using pytest I am getting a low memory warning which I am assuming is due to having multiple test images open (20+). How would I go about cleaning these or closing them? Due to the set up of my code fig.close() won't work. I have attached an example of what one of my tests look like below.

@pytest.mark.mpl_image_compare(baseline_dir='baseline',
                           filename='file.png',
                           style=('style_guidline'),
                           savefig_kwargs={'bbox_inches': 'tight'},
                           tolerance=5)
def test_3(self):
    data = pd.read_csv('test.csv')
    fig = module.create_figure(
    data=data,
    kind="bar_chart",
    )
    return fig

Upvotes: 0

Views: 565

Answers (1)

Brad Solomon
Brad Solomon

Reputation: 40878

One foolproof solution would be to close all open Figures:

>>> plt.close('all')

Example:

>>> import matplotlib.pyplot as plt
... 

>>> fig1, ax1 = plt.subplots()
... fig2, ax2 = plt.subplots()  # 2 separate figures
... 

>>> plt.get_fignums()
... 
[1, 2]

>>> plt.close('all')

>>> plt.get_fignums()
... 
[]

Other options here:

https://matplotlib.org/api/_as_gen/matplotlib.pyplot.close.html

Upvotes: 1

Related Questions