Python plt: close or clear figure does not work

2024/4/14 9:20:03

I generate a lots of figures with a script which I do not display but store to harddrive. After a while I get the message

/usr/lib/pymodules/python2.7/matplotlib/pyplot.py:412: 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. (To control this warning, see the rcParam figure.max_num_figures).max_open_warning, RuntimeWarning)

Thus, I tried to close or clear the figures after storing. So far, I tried all of the followings but no one works. I still get the message from above.

plt.figure().clf()
plt.figure().clear()
plt.clf()
plt.close()
plt.close('all')
plt.close(plt.figure())

And furthermore I tried to restrict the number of open figures by

plt.rcParams.update({'figure.max_num_figures':1})

Here follows a piece of sample code that behaves like described above. I added the different options I tried as comments at the places I tried them.

from pandas import DataFrame
from numpy import random
df = DataFrame(random.randint(0,10,40))import matplotlib.pyplot as plt
plt.ioff()
#plt.rcParams.update({'figure.max_num_figures':1})
for i in range(0,30):fig, ax = plt.subplots()ax.hist([df])plt.savefig("/home/userXYZ/Development/pic_test.png")#plt.figure().clf()#plt.figure().clear()#plt.clf()#plt.close() # results in an error#plt.close('all') # also error#plt.close(plt.figure()) # also error

To be complete, that is the error I get when using plt.close:

can't invoke "event" command: application has been destroyedwhile executing "event generate $w <>"(procedure "ttk::ThemeChanged" line 6)invoked from within "ttk::ThemeChanged"

Answer

The correct way to close your figures would be to use plt.close(fig), as can be seen in the below edit of the code you originally posted.

from pandas import DataFrame
from numpy import random
df = DataFrame(random.randint(0,10,40))import matplotlib.pyplot as plt
plt.ioff()
for i in range(0,30):fig, ax = plt.subplots()ax.hist(df)        name = 'fig'+str(i)+'.png'  # Note that the name should change dynamicallyplt.savefig(name)plt.close(fig)              # <-- use this line

The error that you describe at the end of your question suggests to me that your problem is not with matplotlib, but rather with another part of your code (such as ttk).

https://en.xdnf.cn/q/72848.html

Related Q&A

PCA of RGB Image

Im trying to figure out how to use PCA to decorrelate an RGB image in python. Im using the code found in the OReilly Computer vision book:from PIL import Image from numpy import *def pca(X):# Principa…

delete the first element in subview of a matrix

I have a dataset like this:[[0,1],[0,2],[0,3],[0,4],[1,5],[1,6],[1,7],[2,8],[2,9]]I need to delete the first elements of each subview of the data as defined by the first column. So first I get all elem…

How to scroll QListWidget to selected item

The code below creates a single dialog window with QListWidget and QPushButton. Clicking the button fires up a scroll() function which finds and selects an "ITEM-0011". I wonder if there is a…

Declaring Subclass without passing self

I have an abstract base class Bicycle:from abc import ABC, abstractmethodclass Bicycle(ABC):def __init__(self, cadence = 10, gear = 10, speed = 10):self._cadence = cadenceself._gear = gear self…

Flask-OIDC with keycloak - oidc_callback default callback not working

Im trying to use Flask-oidc in a simple flask application in order to add authentication via keycloak. However, once I log-in with valid credentials it goes back to /oidc_callback which doesnt exist. T…

Matplotlib: reorder subplots

Say that I have a figure fig which contains two subplots as in the example from the documentation:I can obtain the two axes (the left one being ax1 and the right one ax2) by just doing:ax1, ax2 = fig.a…

Filter values in a list using an array with boolean expressions

I have a list of tuples like this:listOfTuples = [(0, 1), (0, 2), (3, 1)]and an array that could look like this:myArray = np.array([-2, 9, 5])Furthermore, I have an array with Boolean expressions which…

Show two correlation coefficients on pairgrid plot with hue (categorical variable) - seaborn python

I found a function to compute a correlation coefficient and then add it to a pair plot (shown below). My issue is that when I run a pairplot with hue (a categorical variable) the correlation coefficien…

How to properly setup vscode with pyside? Missing suggestions

Im very new to pyside, qt and python. I managed to setup a project with a basic window and a push button which closes the app. My problem is, that somehow vscode wont show all properties available, eve…

Split marker and line in Legend - Matplotlib

I want to make a legend where I specify the value for the markers and the value for the lines but not the combination of both.This example should help to illustrate my goal:import matplotlib.pyplot as …