Finlandia_C
Finlandia_C

Reputation: 395

Creating a line plot in python using data from a-for loop

I have some previous code which will print out

'The number for january is x' - etc, throughout one year.

I'm trying to plot the x vs the months using this:

import matplotlib.pyplot as plt
for m, n in result.items():
    print 'The number for', m, "is", n
    plt.plot([n])
    plt.ylabel('Number')
    plt.xlabel('Time (Months)')
    plt.title('Number per month')
    plt.show()

Where m is the month (also the file name it reads from and n is the x value (number).

However when I run this I just get a blank graph - I think I may be missing somethhing major out?

Result contains:

{'apr': 13, 'jun': 13, 'jul': 13, 'aug': 13, 'sep': 13, 'oct': 13} x 6 times 

For practical purposes I made each file have a number of 13 as the real files are enormous

Upvotes: 0

Views: 2721

Answers (1)

Srivatsan
Srivatsan

Reputation: 9363

import matplotlib.pyplot as plt
import numpy as np 

result = {'apr': 13, 'jun': 13, 'jul': 13, 'aug': 13, 'sep': 13, 'oct': 13}
for m, n in result.items():
    print 'The number for', m, "is", n
plt.plot(result.values())
plt.ylabel('Number')
plt.xlabel('Time (Months)')
plt.title('Number per month')
plt.xticks(range(len(result)), result.keys())
plt.show()

So what I have done here is to just remove the plotting section outside the for loop. Now you will get your results printed as you have been doing previously, but the plotting will be done for all the values once.

You can take out the values from a dictionary using dict.values, in our case gives us all the many values which are 13.

enter image description here

Upvotes: 1

Related Questions