Drawing confidence level ellipses

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

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)

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:

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)

1 Like

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

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

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.

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)

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

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


engine = pyttsx3.init(‘sapi5’)

voices = engine.getProperty(‘voices’)

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

def speak(audio):



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


    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:


    r.pause_threshold = 1

    audio = r.listen(source)



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

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

except Exception as e:


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

     return "None"

return query

if name == ‘main’:


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



    elif 'open youtube' in query:


    elif 'open anime' in query:


    elif 'open github' in query:


    elif 'open google' in query:


    elif 'initiate admin' in query:


    elif 'open facebook' in query:


    elif 'open twitter' in query:


    elif 'play music' in query:

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

        songs = os.listdir(music_dir)


        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"


    elif 'open discord' in query:

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


    elif 'open fortnite' in query:

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


    elif 'open gta' in query:

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


    elif 'open player' in query:

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


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 :blush: