Calling pylab.savefig without display in ipython

前端 未结 2 1905
鱼传尺愫
鱼传尺愫 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.

    0 讨论(0)
  • 2020-12-02 05:23

    This is a matplotlib question, and you can get around this by using a backend that doesn't display to the user, e.g. 'Agg':

    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    
    plt.plot([1,2,3])
    plt.savefig('/tmp/test.png')
    

    EDIT: If you don't want to lose the ability to display plots, turn off Interactive Mode, and only call plt.show() when you are ready to display the plots:

    import matplotlib.pyplot as plt
    
    # Turn interactive plotting off
    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('/tmp/test0.png')
    plt.close(fig)
    
    # Create a new figure, plot into it, then don't close it so it does get displayed
    plt.figure()
    plt.plot([1,3,2])
    plt.savefig('/tmp/test1.png')
    
    # Display all "open" (non-closed) figures
    plt.show()
    
    0 讨论(0)
提交回复
热议问题