繁体   English   中英

如何在matplotlib中绘制平均线?

[英]how to plot an average line in matplotlib?

我有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中是否有任何直接方法可将平均线添加到图中? 感谢帮助..

r1是一个字符串列表,而不是实际的floats/ints因此显然您不能将字符串除以int,您需要在传递lambda之前将其强制转换为float或将列表内容转换为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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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