Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python matplotlib - contour plot - confidence intervals

I'm trying to plot contours (doable) on a grid of data using matplotlib.pyplot.contour, but with the contours placed at 1, 2 and 3 sigma away from the peak value. Is there a neat way to do this apart from brute force? Thanks!

Python version is

Python 2.7.2 |EPD 7.2-2 (64-bit)| (default, Sep 7 2011, 16:31:15) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin

like image 799
jtlz2 Avatar asked Jun 09 '12 18:06

jtlz2


People also ask

How do you calculate 95 confidence interval in Python?

Create a new sample based on our dataset, with replacement and with the same number of points. Calculate the mean value and store it in an array or list. Repeat the process many times (e.g. 1000) On the list of the mean values, calculate 2.5th percentile and 97.5th percentile (if you want a 95% confidence interval)

How do you graph a confidence interval in time series Python?

MatPlotLib with Python Initialize a variable, n_steps, to get the mean and standard deviation. Get the under and above lines for confidence intervals. Plot the mean line using plot() method. Use fill_between() method to get the confidence interval.


1 Answers

You can specify a list of z-values where the contours are drawn. So all you have to do is collect the correct z-values for your distribution. Here is an example for '1, 2, and 3 sigma away from the peak value':

enter image description here

Code:

import numpy as np
import matplotlib.cm as cm
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

#Set up the 2D Gaussian:
delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-3.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
sigma = 1.0
Z = mlab.bivariate_normal(X, Y, sigma, sigma, 0.0, 0.0)
#Get Z values for contours 1, 2, and 3 sigma away from peak:
z1 = mlab.bivariate_normal(0, 1 * sigma, sigma, sigma, 0.0, 0.0)
z2 = mlab.bivariate_normal(0, 2 * sigma, sigma, sigma, 0.0, 0.0)
z3 = mlab.bivariate_normal(0, 3 * sigma, sigma, sigma, 0.0, 0.0)

plt.figure()
#plot Gaussian:
im = plt.imshow(Z, interpolation='bilinear', origin='lower',
                 extent=(-50,50,-50,50),cmap=cm.gray)
#Plot contours at whatever z values we want:
CS = plt.contour(Z, [z1, z2, z3], origin='lower', extent=(-50,50,-50,50),colors='red')
plt.savefig('fig.png')
plt.show()
like image 192
fraxel Avatar answered Sep 23 '22 10:09

fraxel