Save plot to image file instead of displaying it using Matplotlib

前端 未结 20 1784
一生所求
一生所求 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: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()
    

提交回复
热议问题