Calling pylab.savefig without display in ipython

前端 未结 2 1904
鱼传尺愫
鱼传尺愫 2020-12-02 05:07

I need to create a figure in a file without displaying it within IPython notebook. I am not clear on the interaction between IPython and matplotlib.pylab<

2条回答
  •  醉梦人生
    2020-12-02 05:20

    We don't need to plt.ioff() or plt.show() (if we use %matplotlib inline). You can test above code without plt.ioff(). plt.close() has the essential role. Try this one:

    %matplotlib inline
    import pylab as plt
    
    # It doesn't matter you add line below. You can even replace it by 'plt.ion()', but you will see no changes.
    ## plt.ioff()
    
    # Create a new figure, plot into it, then close it so it never gets displayed
    fig = plt.figure()
    plt.plot([1,2,3])
    plt.savefig('test0.png')
    plt.close(fig)
    
    # Create a new figure, plot into it, then don't close it so it does get displayed
    fig2 = plt.figure()
    plt.plot([1,3,2])
    plt.savefig('test1.png')
    

    If you run this code in iPython, it will display a second plot, and if you add plt.close(fig2) to the end of it, you will see nothing.

    In conclusion, if you close figure by plt.close(fig), it won't be displayed.

提交回复
热议问题