Save plot to image file instead of displaying it using Matplotlib

前端 未结 20 1370
一生所求
一生所求 2020-11-22 06:07

I am writing a quick-and-dirty script to generate plots on the fly. I am using the code below (from Matplotlib documentation) as a starting point:

from pylab         


        
相关标签:
20条回答
  • 2020-11-22 06:30

    Given that today (was not available when this question was made) lots of people use Jupyter Notebook as python console, there is an extremely easy way to save the plots as .png, just call the matplotlib's pylab class from Jupyter Notebook, plot the figure 'inline' jupyter cells, and then drag that figure/image to a local directory. Don't forget %matplotlib inline in the first line!

    0 讨论(0)
  • 2020-11-22 06:34

    If you don't like the concept of the "current" figure, do:

    import matplotlib.image as mpimg
    
    img = mpimg.imread("src.png")
    mpimg.imsave("out.png", img)
    
    0 讨论(0)
  • 2020-11-22 06:35

    The Solution :

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib
    matplotlib.style.use('ggplot')
    ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
    ts = ts.cumsum()
    plt.figure()
    ts.plot()
    plt.savefig("foo.png", bbox_inches='tight')
    

    If you do want to display the image as well as saving the image use:

    %matplotlib inline
    

    after import matplotlib

    0 讨论(0)
  • 2020-11-22 06:35

    You can do it like this:

    def plotAFig():
      plt.figure()
      plt.plot(x,y,'b-')
      plt.savefig("figurename.png")
      plt.close()
    
    0 讨论(0)
  • 2020-11-22 06:37
    import matplotlib.pyplot as plt
    plt.savefig("image.png")
    

    In Jupyter Notebook you have to remove plt.show() and add plt.savefig(), together with the rest of the plt-code in one cell. The image will still show up in your notebook.

    0 讨论(0)
  • 2020-11-22 06:38

    As suggested before, you can either use:

    import matplotlib.pyplot as plt
    plt.savefig("myfig.png")
    

    For saving whatever IPhython image that you are displaying. Or on a different note (looking from a different angle), if you ever get to work with open cv, or if you have open cv imported, you can go for:

    import cv2

    cv2.imwrite("myfig.png",image)

    But this is just in case if you need to work with Open CV. Otherwise plt.savefig() should be sufficient.

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