Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot rolling mean together with data

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
...

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.

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.

How can I get this to work?

like image 366
JNevens Avatar asked Mar 16 '23 13:03

JNevens


1 Answers

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

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.

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

like image 145
jrjc Avatar answered Mar 23 '23 19:03

jrjc