Save plot to image file instead of displaying it using Matplotlib

前端 未结 20 1417
一生所求
一生所求 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:21

    I used the following:

    import matplotlib.pyplot as plt
    
    p1 = plt.plot(dates, temp, 'r-', label="Temperature (celsius)")  
    p2 = plt.plot(dates, psal, 'b-', label="Salinity (psu)")  
    plt.legend(loc='upper center', numpoints=1, bbox_to_anchor=(0.5, -0.05),        ncol=2, fancybox=True, shadow=True)
    
    plt.savefig('data.png')  
    plt.show()  
    f.close()
    plt.close()
    

    I found very important to use plt.show after saving the figure, otherwise it won't work.figure exported in png

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

    You can either do:

    plt.show(hold=False)
    plt.savefig('name.pdf')
    

    and remember to let savefig finish before closing the GUI plot. This way you can see the image beforehand.

    Alternatively, you can look at it with plt.show() Then close the GUI and run the script again, but this time replace plt.show() with plt.savefig().

    Alternatively, you can use

    fig, ax = plt.figure(nrows=1, ncols=1)
    plt.plot(...)
    plt.show()
    fig.savefig('out.pdf')
    
    0 讨论(0)
  • 2020-11-22 06:22

    The solution is:

    pylab.savefig('foo.png')
    
    0 讨论(0)
  • 2020-11-22 06:25

    After using the plot() and other functions to create the content you want, you could use a clause like this to select between plotting to the screen or to file:

    import matplotlib.pyplot as plt
    
    fig = plt.figure(figsize=(4, 5))       # size in inches
    # use plot(), etc. to create your plot.
    
    # Pick one of the following lines to uncomment
    # save_file = None
    # save_file = os.path.join(your_directory, your_file_name)  
    
    if save_file:
        plt.savefig(save_file)
        plt.close(fig)
    else:
        plt.show()
    
    0 讨论(0)
  • 2020-11-22 06:30

    While the question has been answered, I'd like to add some useful tips when using matplotlib.pyplot.savefig. The file format can be specified by the extension:

    from matplotlib import pyplot as plt
    
    plt.savefig('foo.png')
    plt.savefig('foo.pdf')
    

    Will give a rasterized or vectorized output respectively, both which could be useful. In addition, you'll find that pylab leaves a generous, often undesirable, whitespace around the image. Remove it with:

    savefig('foo.png', bbox_inches='tight')
    
    0 讨论(0)
  • 2020-11-22 06:30

    The other answers are correct. However, I sometimes find that I want to open the figure object later. For example, I might want to change the label sizes, add a grid, or do other processing. In a perfect world, I would simply rerun the code generating the plot, and adapt the settings. Alas, the world is not perfect. Therefore, in addition to saving to PDF or PNG, I add:

    with open('some_file.pkl', "wb") as fp:
        pickle.dump(fig, fp, protocol=4)
    

    Like this, I can later load the figure object and manipulate the settings as I please.

    I also write out the stack with the source-code and locals() dictionary for each function/method in the stack, so that I can later tell exactly what generated the figure.

    NB: Be careful, as sometimes this method generates huge files.

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