【问题标题】:how to plot an average line in matplotlib?如何在 matplotlib 中绘制平均线?
【发布时间】:2015-07-13 20:08:32
【问题描述】:

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

【问题讨论】:

    标签: python list matplotlib average


    【解决方案1】:

    r1 是一个字符串列表,不是实际的floats/ints,所以显然你不能将一个字符串除以一个 int,你需要在你的 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)
    

    【讨论】:

    • 这个错误肯定是因为我在回答中指出的,还有你为什么要使用reduce来获取平均值?
    猜你喜欢
    • 2013-04-17
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2018-06-09
    • 1970-01-01
    • 1970-01-01
    • 2019-06-09
    • 2013-01-20
    相关资源
    最近更新 更多