我有2个列表用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)]
我编写了一个代码来使用这两个列表绘制图形,如下所示:
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()
我添加了这组代码来绘制列表r1的平均值,即:
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()
但代码开始抛出错误说:
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'
在matplotlib中是否有任何直接方法可以将平均线添加到图形中? 谢谢你的帮助......
答案 0 :(得分:1)
r1
是一个不是实际floats/ints
的字符串列表,所以很明显你不能用字符串来划分字符串,你需要在lambda中强制转换为float
或转换列表内容在你通过它之前漂浮:
r1 = ['14.5', '5.5', '21', '19', '25', '25']
r1[:] = map(float,r1)
改变确实有效:
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
使用sum也可以更简单地获得平均值:
avg = sum(r1) / len(r1)