Choosing which figures to show on-screen and which to save to a file using Python's matplotlib

后端 未结 2 1770
[愿得一人]
[愿得一人] 2021-02-20 06:53

I\'d like to create different figures in Python using matplotlib.pyplot. I\'d then like to save some of them to a file, while others should be shown on-screen using

相关标签:
2条回答
  • 2021-02-20 06:59

    Generally speaking, you can just close the figure. As a quick example:

    import matplotlib.pyplot as plt
    
    fig1 = plt.figure()
    plt.plot(range(10), 'ro-')
    plt.title('This figure will be saved but not shown')
    fig1.savefig('fig1.png')
    plt.close(fig1)
    
    fig2 = plt.figure()
    plt.plot(range(10), 'bo')
    plt.title('This figure will be shown')
    
    plt.show()
    

    As far as whether or not the first plt.figure() call is superflous, it depends on what you're doing. Usually, you want to hang on to the figure object it returns and work with that instead of using matplotlib's matlab-ish state machine interface.

    When you're making more complex plots, it often becomes worth the extra line of code to do something like this:

    fig = plt.figure()
    ax = fig.add_subplot(1,1,1)
    ax.plot(range(10))
    

    The advantage is that you don't have to worry about which figure or axis is "active", you just refer to a specific axis or figure object.

    0 讨论(0)
  • 2021-02-20 07:15

    The better way is to use plt.clf() instead of plt.close(). Moreover plt.figure() creates a new graph while you can just clear previous one with plt.clf():

    import matplotlib.pyplot as plt
    
    y1 = [4, 2, 7, 3]
    y2 = [-7, 0, -1, -3]
    
    plt.figure()
    plt.plot(y1)
    plt.savefig('figure1.png')
    plt.clf()
    
    plt.plot(y2)
    
    plt.show()
    plt.clf()
    

    This code will not generate errors or warnings such can't invoke "event" command...

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