When to use cla(), clf() or close() for clearing a plot in matplotlib?

前端 未结 3 2108
北荒
北荒 2020-11-22 09:03

Matplotlib offers there functions:

cla()   # Clear axis
clf()   # Clear figure
close() # Close a figure window

The documentation doesn\'t o

3条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 09:25

    There is just a caveat that I discovered today. If you have a function that is calling a plot a lot of times you better use plt.close(fig) instead of fig.clf() somehow the first does not accumulate in memory. In short if memory is a concern use plt.close(fig) (Although it seems that there are better ways, go to the end of this comment for relevant links).

    So the the following script will produce an empty list:

    for i in range(5):
        fig = plot_figure()
        plt.close(fig)
    # This returns a list with all figure numbers available
    print(plt.get_fignums())
    

    Whereas this one will produce a list with five figures on it.

    for i in range(5):
        fig = plot_figure()
        fig.clf()
    # This returns a list with all figure numbers available
    print(plt.get_fignums())
    

    From the documentation above is not clear to me what is the difference between closing a figure and closing a window. Maybe that will clarify.

    If you want to try a complete script there you have:

    import numpy as np
    import matplotlib.pyplot as plt
    x = np.arange(1000)
    y = np.sin(x)
    
    for i in range(5):
        fig = plt.figure()
        ax = fig.add_subplot(1, 1, 1)
        ax.plot(x, y)
        plt.close(fig)
    
    print(plt.get_fignums())
    
    for i in range(5):
        fig = plt.figure()
        ax = fig.add_subplot(1, 1, 1)
        ax.plot(x, y)
        fig.clf()
    
    print(plt.get_fignums())
    

    If memory is a concern somebody already posted a work-around in SO see: Create a figure that is reference counted

提交回复
热议问题