bbartling
bbartling

Reputation: 3502

plot data 2.5% percentiles 97.5% percentiles

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()

enter image description here

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

Answers (2)

Sergey Bushmanov
Sergey Bushmanov

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");

enter image description here

Upvotes: 1

jfaccioni
jfaccioni

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:

enter image description here

Upvotes: 1

Related Questions