# Drawing confidence level ellipses

**URL:** <https://discuss.python.org/t/drawing-confidence-level-ellipses/4701>\
**Category:** Python Help\
**Created:** [July 12, 2020, 8:56pm UTC](https://discuss.python.org/t/drawing-confidence-level-ellipses/4701 "2020-07-12T20:56:07Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![DarkKnight](https://avatars.discourse-cdn.com/v4/letter/d/b77776/32.png) [@DarkKnight](https://discuss.python.org/u/DarkKnight)\
**Post date:** [July 12, 2020, 8:56pm UTC](https://discuss.python.org/t/drawing-confidence-level-ellipses/4701/1 "2020-07-12T20:56:07Z")

</div>

My model predicts value of some quantity A and B which should fitted to the experimental 1-sigma,2-sigma etc.confidence intervals. I have given a experimental data file containing the experimental output of A,B and delta\_chi\_square Similar to this  
A. B. Chi\_sq  
0.0001 0.170 5.883053e+02  
0.0002 0.175 5.818523e+02  
0.0003 0.180 5.756402e+02  
0.0004 0.185 5.696054e+02  
0.0005 0.190 5.638476e+02  
0.0006 0.195 5.584292e+02  
0.0007 0.200 5.532851e+02  
0.0008 0.205 5.484670e+02  
0.0009 0.210 5.439196e+02  
0.0010 0.215 5.396868e+02  
0.0011 0.220 5.342531e+02  
0.0012 0.225 5.259659e+02  
How to plot the confidence regions on the same modelled data plot by matplotlib

---

<div class="post-metadata">

**Author:** ![lrjball](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/lrjball/32/2321_2.png) [@lrjball](https://discuss.python.org/u/lrjball)\
**Post date:** [July 14, 2020, 6:52pm UTC](https://discuss.python.org/t/drawing-confidence-level-ellipses/4701/2 "2020-07-14T18:52:57Z")

</div>

If you want to plot standard error bars, then you can use matplotlibs `errorbar` (see here: [https://matplotlib.org/3.1.1/api/\_as\_gen/matplotlib.pyplot.errorbar.html](https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.errorbar.html))

You can also create a confidence interval as an envelope by using `fill_between`. There is a good example of that in the matplotlib docs:

```python
N = 21
x = np.linspace(0, 10, 11)
y = [3.9, 4.4, 10.8, 10.3, 11.2, 13.1, 14.1, 9.9, 13.9, 15.1, 12.5]

# fit a linear curve an estimate its y-values and their error.
a, b = np.polyfit(x, y, deg=1)
y_est = a * x + b
y_err = x.std() * np.sqrt(1/len(x) +
                          (x - x.mean())**2 / np.sum((x - x.mean())**2))

fig, ax = plt.subplots()
ax.plot(x, y_est, '-')
ax.fill_between(x, y_est - y_err, y_est + y_err, alpha=0.2)
ax.plot(x, y, 'o', color='tab:brown')

```

(Taken from [https://matplotlib.org/gallery/lines\_bars\_and\_markers/fill\_between\_demo.html#example-confidence-bands](https://matplotlib.org/gallery/lines_bars_and_markers/fill_between_demo.html#example-confidence-bands))

---

<div class="post-metadata">

**Author:** ![DarkKnight](https://avatars.discourse-cdn.com/v4/letter/d/b77776/32.png) [@DarkKnight](https://discuss.python.org/u/DarkKnight)\
**Post date:** [July 15, 2020, 6:36am UTC](https://discuss.python.org/t/drawing-confidence-level-ellipses/4701/4 "2020-07-15T06:36:39Z")

</div>

Thanks for your reply but I am asking for confidence ellipses like the below figure

 ![Contour-lines-represent-the-1-2-3-sigma-confidence-regions-on-the-joint-variation.png](https://us1.discourse-cdn.com/flex002/uploads/python1/original/2X/c/c1fa6a997c50aceb737075094624429959bca0ec.png)

---

<div class="post-metadata">

**Author:** ![lrjball](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/lrjball/32/2321_2.png) [@lrjball](https://discuss.python.org/u/lrjball)\
**Post date:** [July 15, 2020, 11:26am UTC](https://discuss.python.org/t/drawing-confidence-level-ellipses/4701/5 "2020-07-15T11:26:21Z")

</div>

Okay so the plot you have linked looks to be a contour plot, which can be made using `matplotlib.pyplot.contour`. ([https://matplotlib.org/3.1.1/api/\_as\_gen/matplotlib.pyplot.contour.html](https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.contour.html)) However, this requires a 2d array of ‘heights’ for the contours which I’m not sure you have.

Maybe this example from the matplotlib docs is closer to what you want: [https://matplotlib.org/3.2.2/gallery/statistics/confidence\_ellipse.html#sphx-glr-gallery-statistics-confidence-ellipse-py](https://matplotlib.org/3.2.2/gallery/statistics/confidence_ellipse.html#sphx-glr-gallery-statistics-confidence-ellipse-py)

The example uses the pearson correlation coeff between two 1d datasets to plot a confidence ellipse, maybe you are looking to do something different but it should be a good start.

Ultimately, if you are trying to do anything really niche then it will not be built in to matplotlib, but you will be able to build it yourself using matplotlibs ellipses and other shapes. So if you know the formula for the ellipses you want to draw, you can always just draw them over the plot.

---

<div class="post-metadata">

**Author:** ![DarkKnight](https://avatars.discourse-cdn.com/v4/letter/d/b77776/32.png) [@DarkKnight](https://discuss.python.org/u/DarkKnight)\
**Post date:** [July 15, 2020, 12:13pm UTC](https://discuss.python.org/t/drawing-confidence-level-ellipses/4701/6 "2020-07-15T12:13:26Z")

</div>

Thank you very much for your reply, actually I have some experimental data attatched below in which first two coloumns are measured values of two quantities and the third column corresponds to delta chi square, so is this possible to get the confidence ellipse for such data

(Attachment data-NO.txt is missing)

---

<div class="post-metadata">

**Author:** ![lrjball](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/lrjball/32/2321_2.png) [@lrjball](https://discuss.python.org/u/lrjball)\
**Post date:** [July 16, 2020, 8:34pm UTC](https://discuss.python.org/t/drawing-confidence-level-ellipses/4701/7 "2020-07-16T20:34:01Z")

</div>

Hi @DarkKnight, do the links I provided above help you to create the plot? If some of the examples look like what you are trying to make, then see if you can create them using your data.  
Unfortunately I won’t be writing the code for you, but can point you in the right direction if you are trying to do something not shown in the above examples. For that thought you will need to better explain what you are trying to build.  
Likewise if you are having trouble implementing the above then show what you have tried so far and someone may be able help you out

---

<div class="post-metadata">

**Author:** ![asfandyaar](https://avatars.discourse-cdn.com/v4/letter/a/eb9ed0/32.png) [@asfandyaar](https://discuss.python.org/u/asfandyaar)\
**Post date:** [July 18, 2020, 9:25am UTC](https://discuss.python.org/t/drawing-confidence-level-ellipses/4701/8 "2020-07-18T09:25:10Z")

</div>

hello,  
i was wondering if you could help me

this my my code but for some reason it dosent work properly  
import pyttsx3

import datetime

import speech\_recognition as sr

import wikipedia

import webbrowser

import os

import pyaudio

import calendar

import random

import warnings

warnings.filterwarnings(‘ignore’)

engine = pyttsx3.init(‘sapi5’)

voices = engine.getProperty(‘voices’)

engine.setProperty(‘voice’, voices[0].id)

def speak(audio):

```
engine.say(audio)

engine.runAndWait()

```

def wishMe():

```
hour = int(datetime.datetime.now().hour)

if hour >= 0 and hour < 12:

    speak("Good Morning!")

elif hour >= 12 and hour < 18:

    speak("Good Afternoon!")

else:

    speak("Good Evening!")

speak("I am Jarvis Sir. Please tell me how may I help you")

```

def takeCommand():

```
r = sr.Recognizer()

with sr.Microphone() as source:

    print("Listening...")

    r.pause_threshold = 1

    audio = r.listen(source)

try:

    print("Recognizing...")

    query = r.recognize_google(audio, language='en-us')

    print(f"User said: {query}\n")

except Exception as e:

     print(e)

     print("Say that again please...")

     return "None"

return query

```

if **name** == ‘ **main** ’:

```
wishMe()

while True:

    query = takeCommand().lower()  

    if 'wikipedia' in query:  

        speak('Searching Wikipedia...')

        query = query.replace("wikipedia", "")

        results = wikipedia.summary(query, sentences=2)

        speak("According to Wikipedia")

        print(results)

        speak(results)

    elif 'open youtube' in query:

        webbrowser.open("youtube.com")

    elif 'open anime' in query:

        webbrowser.open("kaa.si")

    elif 'open github' in query:

        webbrowser.open("github.com")

    elif 'open google' in query:

        webbrowser.open("google.com")

    elif 'initiate admin' in query:

        webbrowser.open("192.168.0.1")

    elif 'open facebook' in query:

        webbrowser.open("https://www.facebook.com")

    elif 'open twitter' in query:

        webbrowser.open("https://twitter.com")

    elif 'play music' in query:

        music_dir = 'C:\\Users\\asfan\\Music'

        songs = os.listdir(music_dir)

        print(songs)

        os.startfile(os.path.join(music_dir, songs[0]))

    elif 'the time' in query:

        strTime = datetime.datetime.now().strftime("%H:%M:%S")

        speak(f"Sir, the time is {strTime}") 

    elif 'open code' in query:

        codepath = "F:\softwares\Microsoft VS Code\Code.exe"

        os.startfile(codepath)

    elif 'open discord' in query:

        discord1 = "C:\\Users\\mg\\AppData\\Local\\Discord\\Update.exe --processStart Discord.exe"

        os.startfile(discord1)

    elif 'open fortnite' in query:

        fortnite1 = "com.epicgames.launcher:/apps/Fortnite?action=launch&silent=true"

        os.startfile(fortnite1)

    elif 'open gta' in query:

        gta1 = "com.epicgames.launcher://apps/9d2d0eb64d5c44529cece33fe2a46482?action=launch&silent=true"

        os.startfile(gta1)

    elif 'open player' in query:

        pubg = "G:\\games\\PUBGLite\\Launcher.exe"

        os.startfile(pubg)
```

---

<div class="post-metadata">

**Author:** ![lrjball](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/lrjball/32/2321_2.png) [@lrjball](https://discuss.python.org/u/lrjball)\
**Post date:** [July 18, 2020, 10:51am UTC](https://discuss.python.org/t/drawing-confidence-level-ellipses/4701/9 "2020-07-18T10:51:35Z")

</div>

Hi @asfandyaar,

I’m sure someone will be happy to help you, but you have posted this on the wrong thread. You would be best to start a new thread in ‘Users’ and then people will be able to find your post and help you out.

Also, if possible try to give the smallest amount of code that reproduces the error, as that will make it easier for the people helping you. It is also worth mentioning gexactlt what error you are facing, so that people don’t have to try and run your code to find the issue.

Good luck 😊
