Reputation: 141
I got 2 lists to plot a time series graph using matplotlib
r1=['14.5', '5.5', '21', '19', '25', '25']
t1=[datetime.datetime(2014, 4, 12, 0, 0), datetime.datetime(2014, 5, 10, 0, 0), datetime.datetime(2014, 6, 12, 0, 0), datetime.datetime(2014, 7, 19, 0, 0), datetime.datetime(2014, 8, 15, 0, 0), datetime.datetime(2014, 9, 17, 0, 0)]
I wrote a code to plot a graph using these two lists, which is as follows:
xy.plot(h,r1)
xy.xticks(h,t1)
xy.plot(r1, '-o', ms=10, lw=1, alpha=1, mfc='orange')
xy.xlabel('Sample Dates')
xy.ylabel('Air Temperature')
xy.title('Tier 1 Lake Graph (JOR-01-L)')
xy.grid(True)
xy.show()
I added this set of codes to plot the average of the values of list r1 i.e:
avg= (reduce(lambda x,y:x+y,r1)/len(r1))
avg1.append(avg)
avg2=avg1*len(r1)
xy.plot(h,avg2)
xy.plot(h,r1)
xy.xticks(h,t1)
xy.plot(r1, '-o', ms=10, lw=1, alpha=1, mfc='orange')
xy.xlabel('Sample Dates')
xy.ylabel('Air Temperature')
xy.title('Tier 1 Lake Graph (JOR-01-L)')
xy.grid(True)
xy.show()
but the code started throwing an error saying:
Traceback (most recent call last):
File "C:\Users\Ayush\Desktop\UWW Data Examples\new csvs\temp.py", line 63, in <module>
avg= (reduce(lambda x,y:x+y,r1)/len(r1))
TypeError: unsupported operand type(s) for /: 'str' and 'int'
Is there any direct method in matplotlib to add an average line into a graph?? Thanks for help..
Upvotes: 2
Views: 8776
Reputation: 180401
r1
is a list of strings not actual floats/ints
so obviously you cannot divide a string by a an int, you need to cast to float
in your lambda or convert the list content to floats before you pass it:
r1 = ['14.5', '5.5', '21', '19', '25', '25']
r1[:] = map(float,r1)
The change does work:
In [3]: r1=['14.5', '5.5', '21', '19', '25', '25']
In [4]: avg= (reduce(lambda x,y:x+y,r1)/len(r1))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-91fbcb81cdb6> in <module>()
----> 1 avg= (reduce(lambda x,y:x+y,r1)/len(r1))
TypeError: unsupported operand type(s) for /: 'str' and 'int'
In [5]: r1[:] = map(float,r1)
In [6]: avg= (reduce(lambda x,y:x+y,r1)/len(r1))
In [7]: avg
Out[7]: 18.333333333333332
Also using sum would be a lot simpler to get the average:
avg = sum(r1) / len(r1)
Upvotes: 1