Difference between plt.close() and plt.clf()

前端 未结 4 1646
猫巷女王i
猫巷女王i 2020-12-29 03:49

In Python, what is the difference between plt.clf() and plt.close()?

Will they function the same way?

相关标签:
4条回答
  • 2020-12-29 04:31

    plt.close() will close the figure window entirely, where plt.clf() will just clear the figure - you can still paint another plot onto it.

    It sounds like, for your needs, you should be preferring plt.clf(), or better yet keep a handle on the line objects themselves (they are returned in lists by plot calls) and use .set_data on those in subsequent iterations.

    0 讨论(0)
  • 2020-12-29 04:32

    plt.clf() clears the entire current figure with all its axes, but leaves the window opened, such that it may be reused for other plots.

    plt.close() closes a window, which will be the current window, if not specified otherwise.

    0 讨论(0)
  • 2020-12-29 04:32

    There is a slight difference between the two functions.

    plt.close() - It altogether plots the graph in seperate windows,releasing memory,retaining each window for view.

    plt.clf() - We can say,it displays the graph in the same window one after other

    For illustration, I have plotted two graphs with paramters year and views on X axis and Y axis each. Initially I have used closed function.it displayed the graphs in two seperate windows…

    Afterwords, when I run the program with clf() it clears the graph and displays next one in same window i.e figure 1. Here is the code snippet -

        import matplotlib.pyplot as plt
        year = [2001,2002,2003,2004]
        Views= [12000,14000,16000,18000]
        Views2 = [15000,1800,24000,84000]
        plt.plot(year,Views)
        plt.show()
        plt.clf()
        plt.plot(year,Views2)
        plt.show()
        plt.clf()
    

    image 1 with close function


    image 2 with close function


    image 1 with clf function


    image 2 with clf function


    0 讨论(0)
  • 2020-12-29 04:42

    I think it is worth mentioning that plt.close() releases the memory, thus is preferred when generating and saving many figures in one run.

    Using plt.clf() in such case will produce a warning after 20 plots (even if they are not going to be shown by plt.show()):

    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.

    0 讨论(0)
提交回复
热议问题