Reputation: 3502
Im working with times series data so for SO purposes Ill make some up..
import pandas as pd
import numpy as np
from numpy.random import randint
import matplotlib.pyplot as plt
rng = pd.date_range('10/9/2018 00:00', periods=10, freq='1H')
df = pd.DataFrame({'Random_Number':randint(1, 100, 10)}, index=rng)
If I plot this it looks like this: df.plot()
I can print the values of df
upper and lower percentiles:
df.quantile(0.025)
df.quantile(0.975)
But how would I add lines to my chart to represent the 2.5th percentile and 97.5th percentile of the dataset?
Upvotes: 3
Views: 2653
Reputation: 25199
You can do:
import pandas as pd
import numpy as np
from numpy.random import randint
import matplotlib.pyplot as plt
rng = pd.date_range('10/9/2018 00:00', periods=10, freq='1H')
df = pd.DataFrame({'Random_Number':randint(1, 100, 10)}, index=rng)
df.plot()
plt.hlines(df.quantile(0.025), xmin=min(rng), xmax=max(rng), linestyle="--", color="r")
plt.hlines(df.quantile(0.975), xmin=min(rng), xmax=max(rng), linestyle="--", color="r");
Upvotes: 1
Reputation: 7519
Use plt.axhline
for plotting a horizontal line at a specific Y value (conversively, there's plt.axvline
for plotting a vertical line at a specific X value):
import pandas as pd
import numpy as np
from numpy.random import randint
import matplotlib.pyplot as plt
np.random.seed(10) # added for reproductibility
rng = pd.date_range('10/9/2018 00:00', periods=10, freq='1H')
df = pd.DataFrame({'Random_Number':randint(1, 100, 10)}, index=rng)
df.plot()
plt.axhline(df.quantile(0.025)[0])
plt.axhline(df.quantile(0.975)[0])
plt.show()
Plot produced:
Upvotes: 1