绘图滚动平均值和数据 [英] Plot rolling mean together with data

查看:62
本文介绍了绘图滚动平均值和数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的 DataFrame:

I have a DataFrame that looks something like this:

####delays:
            Worst case  Avg case
2014-10-27    2.861433  0.953108
2014-10-28    2.899174  0.981917
2014-10-29    3.080738  1.030154
2014-10-30    2.298898  0.711107
2014-10-31    2.856278  0.998959
2014-11-01    3.118587  1.147104
...

我想绘制此DataFrame的数据以及数据的滚动平均值.我希望数据本身应该是一条虚线,而滚动平均值应该是一条实线.最坏情况的列应为红色,而平均情况的列应为蓝色.

I would like to plot the data of this DataFrame, together with the rolling mean of the data. I would like the data itself should be a dotted line and the rolling mean to be a full line. The worst case column should be in red, while the average case column should be in blue.

我尝试了以下代码:

import pandas as pd
import matplotlib.pyplot as plt

rolling = pd.rolling_mean(delays, 7)
delays.plot(x_compat=True, style='r--')
rolling.plot(style='r')
plt.title('Delays per day on entire network')
plt.xlabel('Date')
plt.ylabel('Minutes')
plt.show()

不幸的是,这给了我 2 个不同的情节.一种带有数据,另一种带有滚动平均值.此外,最坏情况列和平均情况列都是红色的.

Unfortunately, this gives me 2 different plots. One with the data and one with the rolling mean. Also, the worst case column and average case column are both in red.

我怎样才能让它发挥作用?

How can I get this to work?

推荐答案

你需要告诉 Pandas 你想画哪里.默认情况下,pandas 创建一个新图形.

You need to say to pandas where you want to plot. By default pandas creates a new figure.

只需修改这两行:

delays.plot(x_compat=True, style='r--')
rolling.plot(style='r')

作者:

ax_delays = delays.plot(x_compat=True, style='--', color=["r","b"])
rolling.plot(color=["r","b"], ax=ax_delays, legend=0) 

现在在第二行中,告诉熊猫在ax_delays上绘图,并且不再显示图例.

in the 2nd line you now tell pandas to plot on ax_delays, and to not show the legend again.

要获得2行的2种不同颜色,只需使用 color 参数传递尽可能多的颜色即可(见上文).

To get 2 different colors for the 2 lines, just pass as many colors with color argument (see above).

这篇关于绘图滚动平均值和数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆