python - how to plot an average line in matplotlib? -
i got 2 lists plot 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 code plot graph using these 2 lists, 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 set of codes plot average of 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 code started throwing 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) /: 'str' , 'int'
is there direct method in matplotlib add average line graph?? help..
r1
list of strings not actual floats/ints
cannot divide string int, need cast float
in lambda or convert list content floats before pass it:
r1 = ['14.5', '5.5', '21', '19', '25', '25'] r1[:] = map(float,r1)
the change 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) /: 'str' , '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 lot simpler average:
avg = sum(r1) / len(r1)
Comments
Post a Comment