1 year ago

#73898

test-img

Ganonino

Warning when saving plots in loop using Matplotlib

When I run the following code it warns after each loop iteration:

../matplotlib/backends/backend_gtk3.py:181: Warning: Source ID X was not found when attempting to remove it

If i remove the plt.close("all") that I thought was the cause, after 20 iterations it will instead say

RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (matplotlib.pyplot.figure) are retained until explicitly closed and may consume too much memory.

And after it will show the first warning for each ID anyway

    dir_output_path = '/aPath'
    dir_data = '/data'

    pathlist = Path(dir_data).rglob('*.log.parq')

    iter = 0
    for path in pathlist:
    
        # because path is object not string
        path_in_str = str(path)
        df = pd.read_parquet(path_in_str)
    
        df.plot(x="column", y=["aColumn", "anotherColumn"])
    
        # I save plot to .png
        plt.savefig(dir_output_path + 'testPlot' + str(iter) + '.png' , bbox_inches='tight')
        iter += 1
        # If I don't include close it will instead warn 
        # after 20 plots that it might take up a lot of memory
        plt.close("all") 

My best guess is that plt.savefig already removed the plots? This would then make the warning unnecessary, can I safely block this warning from being written to terminal? I'm afraid I'm missing something here and I'll have issues when I scale this up.

python

loops

matplotlib

warnings

0 Answers

Your Answer

Accepted video resources