[Matplotlib drawing tips] Solve the problem of memory overflow, stuck, and blank except for the first picture when Matplotlib draws in batches
When using [Matplotlib] to generate a large number of pictures in batches, the memory will gradually take off and then get stuck. At the beginning, I checked the tutorial and found that the new fig was generated in a loop, and the old fig was not deleted, resulting in a memory explosion. Try to use plt.clf() to clear all the axes, hoping to repeatedly clear and draw on a fig, but all but the first one are blank.
cla() # Clear axis Clears the currently active axis in the current graph. Other axes are not affected. clf() # Clear figure clears all axes, but leaves the window open so it can be reused. close () #Close the window
Put the generation of fig outside the for loop, generate a new coordinate axis in the loop, and call plt.clf() at the end of the loop to clear it.
import matplotlib.pyplot as plt from matplotlib.figure import figaspect from tqdm import tqdm #Used to display progress import numpy as np ratio = 9 / 16 #Set the image ratio the ratio = height / width). w, h = figaspect(ratio) # return width, height is the opposite of ratio, a very magical brain circuit plt.rcParams[ 'figure.figsize' ] = (w, h) #Set the picture size proportionally fig = plt.figure(constrained_layout=True) fig.set_constrained_layout_pads(hspace = 0) gs = fig.add_gridspec( 1 , 1 ) #Set the pictures of how many rows and columns to draw on fig (that is, multiple pictures are on one fig, if only one picture is drawn, just (1, 1)) for i in tqdm(range( 1000 )): #Generate 1000 images t = np.arange( 0.0 , 2.0 , 0.01 ) s = np.sin(2 * i*np.pi * t) ax1 = fig .add_subplot(gs[ 0 , :]) # Give the first line of fig to axis 1 ax1 ax1.plot(t,s, linewidth= 0.75 ) ax1.grid(True, which='both') ax1.set_ylabel('y') ax1.set_xlabel('t') plt.savefig( "./" +str(i)+ ".jpg" ,dpi= 200 ) #Press i.jpg to save the picture plt.clf()