close

How to plot confidence interval in Python?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to plot confidence interval in Python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to plot confidence interval in Python?

  1. How to plot confidence interval in Python?

    Let's assume that we have three categories and lower and upper bounds of confidence intervals of a certain estimator across these three categories:

  2. plot confidence interval in Python

    Let's assume that we have three categories and lower and upper bounds of confidence intervals of a certain estimator across these three categories:

Method 1

There are several ways to accomplish what you asking for:

Using only matplotlib

from matplotlib import pyplot as plt
import numpy as np

#some example data
x = np.linspace(0.1, 9.9, 20)
y = 3.0 * x
#some confidence interval
ci = 1.96 * np.std(y)/np.sqrt(len(x))

fig, ax = plt.subplots()
ax.plot(x,y)
ax.fill_between(x, (y-ci), (y+ci), color='b', alpha=.1)

fill_between does what you are looking for. For more information on how to use this function

Output

enter image description here

Alternatively, go for seaborn, which supports this using lineplot or regplot

Method 2

Let’s assume that we have three categories and lower and upper bounds of confidence intervals of a certain estimator across these three categories:

data_dict = {}
data_dict['category'] = ['category 1','category 2','category 3']
data_dict['lower'] = [0.1,0.2,0.15]
data_dict['upper'] = [0.22,0.3,0.21]
dataset = pd.DataFrame(data_dict)

You can plot the confidence interval for each of these categories using the following code:

for lower,upper,y in zip(dataset['lower'],dataset['upper'],range(len(dataset))):
    plt.plot((lower,upper),(y,y),'ro-',color='orange')
plt.yticks(range(len(dataset)),list(dataset['category']))

Resulting with the following graph:

Confidence intervals of an estimator across some three categories

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read