简体   繁体   中英

how to plot an average line in matplotlib?

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 ie:

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..

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM