How could I save multiple plots in a folder using Python?

前端 未结 2 706
梦谈多话
梦谈多话 2020-12-17 06:43

Here is my program in python and I am trying to save multiple plots in a single folder but it doesn\'t seem to work. How could I do this please?

for i in ra         


        
相关标签:
2条回答
  • 2020-12-17 07:16

    You can use the savefig function.

    for i in range(0:244):
        plt.figure()
        y = numpy.array(Data_EMG[i,:])
        x = pylab.linspace(EMG_start, EMG_stop, Amount_samples)
        plt.xlabel('Time(ms)')
        plt.ylabel('EMG voltage(microV)')
        plt.savefig('EMG {0}.jpg'.format(i))
        plt.close()
    
    0 讨论(0)
  • 2020-12-17 07:22

    First of all check the identation. Hopefully your code actually reads

    for i in range(0:244):
        plt.figure()
        y = numpy.array(Data_EMG[i,:])
        x = pylab.linspace(EMG_start, EMG_stop, Amount_samples)
        plt.xlabel('Time(ms)')
        plt.ylabel('EMG voltage(microV)')
        pylab.plot(x, y)
        pylab.show(block=True)
    

    At each iteration you completely generate a new figure. That´s very ineffective. Also you just plot your figure on the screen and not actually save it. Better is

    from os import path
    data = numpy.array(Data_EMG)                 # convert complete dataset into numpy-array
    x = pylab.linspace(EMG_start, EMG_stop, Amount_samples) # doesn´t change in loop anyway
    
    outpath = "path/of/your/folder/"
    
    fig, ax = plt.subplots()        # generate figure with axes
    image, = ax.plot(x,data[0])     # initialize plot
    ax.xlabel('Time(ms)')
    ax.ylabel('EMG voltage(microV)')
    plt.draw()
    fig.savefig(path.join(outpath,"dataname_0.png")
    
    for i in range(1, len(data)):
        image.set_data(x,data[i])
        plt.draw()
        fig.savefig(path.join(outpath,"dataname_{0}.png".format(i))
    

    Should be much faster.

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