Singu
Singu

Reputation: 305

how to plot multiple lines while reading x and y from files in a for loop?

I have a for loop in which for every input file I read x and y from the file and save them as I want in separate lists and then plot a graph. Now I want to plot all the x-y of all files in just one plot . The problem is that I'm reading x and y from my files in a for loop so I have to plot them and then go to the next file , otherwise I will lose x and y and I don't want to save them in another file and then plot them together. Are there any suggestions? I would appreciate any advice as it's the first time I'm using matplotlib and I'm new to python.

for f in os.listdir(Source):
x=[]
y=[]
file_name= f
print 'Processing file : ' + str (file_name)
pkl_file = open( os.path.join(Source,f) , 'rb' )
List=pickle.load(pkl_file)
pkl_file.close()
x = [dt.datetime.strptime(i[0],'%Y-%m-%d')for i in List ]
y = [i[1] for i in List]
maxRange=max(y)

if not maxRange >= 5 :
    print 'The word #' +str(file_name[0]) + ' has a frequency of ' +str(maxRange) + '.'
else :
    fig = plt.figure()
    plt.ylim(0,maxRange)
    plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
    plt.gca().xaxis.set_major_locator(mdates.YearLocator())
    plt.plot(x, y , 'm')
    plt.xlabel('Time')
    plt.ylabel('Frequency')
    fig.savefig("Plots/"+ file_name[0] + '.pdf' )

Upvotes: 0

Views: 273

Answers (1)

tktk
tktk

Reputation: 11734

There ya go. Took the liberty of offering a few more recommendations, though not all.

fig = plt.figure()
maxRange = 0
for file_name in os.listdir(source):
    print 'Processing file : ' + str(file_name)
    with open(os.path.join(source,file_name), 'rb') as pkl_file:
        lst = pickle.load(pkl_file)
    x,y = zip(*[(dt.datetime.strptime(x_i,'%Y-%m-%d'), y_i) for (x_i, y_i) in lst])
    if max(y) < 5 :
        print 'The word #' +str(file_name[0]) + ' has a frequency of ' +str(maxRange) + '.'
    else :
        maxRange=max(maxRange, max(y))
        plt.plot(x, y , 'm')
plt.ylim(0,maxRange)
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
plt.gca().xaxis.set_major_locator(mdates.YearLocator())
plt.xlabel('Time')
plt.ylabel('Frequency')
fig.savefig("Plots/allfiles.pdf")

Upvotes: 2

Related Questions