user7852656
user7852656

Reputation: 735

How do I save each plot in individual pdf files while batch processing the x and y for the plot?

I came back to do some python work after not practicing it for a while. I feel like my issue may be a simple problem.. But I'm not sure how to address it. If you could share your insights, it would be a huge help. My current code is as the following:

 import numpy as np
 import matplotlib.pyplot as plt
 import csv
 import os


 myfiles = os.listdir('input') #'all my input files are accessed 

Then I do a whole bunch of math then generate my output files and save them in 'output' folder. Output folders consist output files of which each contains x and y columns as the code suggests in the following.

 with open('output/'+file,'w') as f:    
    for a,b in zip(my_x,my_y):
        f.write('{0:f},{1:f}\n'.format(a,b))

My biggest question lies here in the following, where I want to plot each output file and save them in pdf.

with open('output/'+file,'w') as f:
    for a in zip(my_x,my_y):
        fig, ax = plt.subplots()
        ax.plot(my_x,my_y) 
        plt.xlim(3500,5700)
        plt.show()
        ax.set_ylabel('y_value')
        ax.set_title('x')
        fig.savefig()

The error message I get is

savefig() missing 1 required positional argument: 'fname'

Without the figure part of the code, the code runs fine (reads the input and generates the output files fine).

Any suggestions as to how to save figure for each of the output file?

If my code provided here is not sufficient enough to understand what's going on, let me know. I can provide more!

Upvotes: 0

Views: 151

Answers (1)

DopplerShift
DopplerShift

Reputation: 5843

Would this do what you want?

with open('output/'+file,'w') as f:
    for a in zip(my_x,my_y):
        fig, ax = plt.subplots()
        ax.plot(my_x,my_y) 
        plt.xlim(3500,5700)
        plt.show()
        ax.set_ylabel('y_value')
        ax.set_title('x')
        fig.savefig('output/' + file + '.pdf')

Upvotes: 1

Related Questions