Save plot to image file instead of displaying it using Matplotlib

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

    According to question Matplotlib (pyplot) savefig outputs blank image.

    One thing should note: if you use plt.show and it should after plt.savefig, or you will give a blank image.

    A detailed example:

    import numpy as np
    import matplotlib.pyplot as plt
    
    
    def draw_result(lst_iter, lst_loss, lst_acc, title):
        plt.plot(lst_iter, lst_loss, '-b', label='loss')
        plt.plot(lst_iter, lst_acc, '-r', label='accuracy')
    
        plt.xlabel("n iteration")
        plt.legend(loc='upper left')
        plt.title(title)
        plt.savefig(title+".png")  # should before plt.show method
    
        plt.show()
    
    
    def test_draw():
        lst_iter = range(100)
        lst_loss = [0.01 * i + 0.01 * i ** 2 for i in xrange(100)]
        # lst_loss = np.random.randn(1, 100).reshape((100, ))
        lst_acc = [0.01 * i - 0.01 * i ** 2 for i in xrange(100)]
        # lst_acc = np.random.randn(1, 100).reshape((100, ))
        draw_result(lst_iter, lst_loss, lst_acc, "sgd_method")
    
    
    if __name__ == '__main__':
        test_draw()
    

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

    Additionally to those above, I added __file__ for the name so the picture and Python file get the same names. I also added few arguments to make It look better:

    # Saves a PNG file of the current graph to the folder and updates it every time
    # (nameOfimage, dpi=(sizeOfimage),Keeps_Labels_From_Disappearing)
    plt.savefig(__file__+".png",dpi=(250), bbox_inches='tight')
    # Hard coded name: './test.png'
    
    0 讨论(0)
提交回复
热议问题