0

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' )

1 Answer 1

2

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")
Sign up to request clarification or add additional context in comments.

4 Comments

thank you so much , it sounds really good. I'm trying to make it run but I'm getting some invalid syntax error near the if not max(y) , I'm trying to figure out what's the problem as soon as I run it , I will give you feedback.
@Singu Missed a closing bracket. try now.
Thank you so much. it works! but is there any way that I can have different colors in order to recognize each line is for which word?
@Singu take a look at colormaps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.