pandas 将滚动均值与数据一起绘制
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29417763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Plot rolling mean together with data
提问by JNevens
I have a DataFrame that looks something like this:
我有一个看起来像这样的 DataFrame:
####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
...
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.
我想绘制此 DataFrame 的数据以及数据的滚动平均值。我希望数据本身应该是一条虚线,而滚动平均值应该是一条实线。最坏情况列应为红色,而平均情况列应为蓝色。
I've tried the following code:
我试过以下代码:
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()
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.
不幸的是,这给了我 2 个不同的情节。一种是数据,一种是滚动平均值。此外,最坏情况列和平均情况列都是红色的。
How can I get this to work?
我怎样才能让它工作?
回答by jrjc
You need to say to pandas where you want to plot. By default pandas creates a new figure.
你需要告诉Pandas你想在哪里绘制。默认情况下,pandas 创建一个新图形。
Just modify these 2 lines:
只需修改这两行:
delays.plot(x_compat=True, style='r--')
rolling.plot(style='r')
by:
经过:
ax_delays = delays.plot(x_compat=True, style='--', color=["r","b"])
rolling.plot(color=["r","b"], ax=ax_delays, legend=0)
in the 2nd line you now tell pandas to plot on ax_delays, and to not show the legend again.
在第二行中,您现在告诉Pandas在 ax_delays 上绘图,并且不再显示图例。
To get 2 different colors for the 2 lines, just pass as many colors with colorargument (see above).
要为 2 行获得 2 种不同的颜色,只需通过color参数传递尽可能多的颜色(见上文)。

