In conclusion, the solution is plt.close ()
.
In jupyter (Google Colab.) Environment, if you want to generate a large number of graphs and save them as an image file using matplotlib, if you do not want to display the graph in the ** execution result cell (on the screen) of the notebook **there is.
In particular, if you try to display more than 20 graphs, you will get the following warning.
/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:8: 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 rcParamfigure.max_open_warning
).
A note on avoiding this issue.
The following code is "generate 40 normal random numbers with an average of 50 and a standard deviation of 10 and draw a histogram of them and save them as a png file".
I'm looping 50 times to see the distribution of each set when I try 50 sets.
A large number of graphs are output in the execution result cell
import numpy as np
import matplotlib.pyplot as plt
#Generate 50 image files
for i in range(50) :
dat = (np.random.normal(50,10,size=40)).astype(np.int64)
plt.figure()
plt.hist(dat,bins=10,range=(0,100))
plt.yticks(range(0,31,10))
plt.xlim(0,100)
plt.ylim(0,30)
plt.savefig(f'fig{i}.png') #Save as image file
When I execute the above code, ** the warning at the beginning is displayed **, and the execution result cell is lined with a large number of graphs, which makes the notebook difficult to see. At the same time, the notebook (xxxx.ipynb
) also contains the image of the execution result, so the file size will also increase.
plt.show ()
.The problem is solved by putting plt.close ()
after outputting the graph to a file plt.savefig (...)
.
Do not output the graph in the execution result cell
import numpy as np
import matplotlib.pyplot as plt
for i in range(50) :
dat = (np.random.normal(50,10,size=40)).astype(np.int64)
plt.figure()
plt.hist(dat,bins=10,range=(0,100))
plt.yticks(range(0,31,10))
plt.xlim(0,100)
plt.ylim(0,30)
plt.savefig(f'fig{i}.png')
plt.close() #■■■ Addition ■■■
When I execute the above code, nothing is output to the execution result cell. Of course, the file output will be done without any problem.
Recommended Posts