Returning plots in repeated function calls without plotting in notebook

I have a function that returns plots without saving images. It uses the pd.DataFrame.plot method to plot the images and return them. I need to call this function repeatedly in a large number of iterations.

The problem is that I can’t modify the function at all, therefore I need to be able to force the function to NOT display an image due to memory issues. Here is a reproducible toy example of the function.

import numpy as np
import pandas as pd

#Can't modify this ->
def fig_gen():
    img = pd.DataFrame(np.random.random((100,2)))
    fig = img.plot()
    return fig

#This is a BIG loop over 5k images
for i in range(4):
    fig_gen().get_figure().savefig('test.png')

I have gone through a bunch of approaches that were answered on Stack Overflow. I have tried using but the figure is still displaying –

plt.ioff()

## and

plt.close(fig)

I can’t use plt.savefig() directly after plotting inside the function as I can’t modify it.

Is there a way I can call the function repeatedly, but force matplotlib to not display the plot and only return the figure object, which I can then save using Figure.savefig() outside the function?

Answer

  • In Jupyter, turn inline plotting off in Jupyter by using %matplotlib qt in a cell prior to plotting. This is a notebook wide setting, so only needs to happen once.
    • Turn inline plotting back on with %matplotlib inline, or going to Kernel and selectingRestart Kernel and Clear All Outputs...
  • Adjust the for-loop as follows:
for i in range(4):
    fig = fig_gen().get_figure()
    fig.savefig(f'test_{i}.png')
    fig.clf()