Skip to content

Instantly share code, notes, and snippets.

@rsnemmen
Created April 1, 2015 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rsnemmen/2e7f735a4305a28114bd to your computer and use it in GitHub Desktop.
Save rsnemmen/2e7f735a4305a28114bd to your computer and use it in GitHub Desktop.
Script illustrating how to do a linear regression and plot the confidence band of the fit
# See also http://astropython.blogspot.in/2011/12/script-illustrating-how-to-do-linear.html
import numpy, pylab, scipy
import nemmen
# Data taken from http://orion.math.iastate.edu/burkardt/data/regression/x01.txt.
# I removed the header from the file and left only the data in 'testdata.dat'.
xdata,ydata = numpy.loadtxt('testdata.dat',unpack=True,usecols=(1,2))
xdata=numpy.log10(xdata) # take the logs
ydata=numpy.log10(ydata)
# Linear fit
a, b, r, p, err = scipy.stats.linregress(xdata,ydata)
# Generates arrays with the fit
x=numpy.linspace(xdata.min(),xdata.max(),100)
y=a*x+b
# Calculates the 2 sigma confidence band contours for the fit
lcb,ucb,xcb=nemmen.confband(xdata,ydata,a,b,conf=0.95)
# Plots the fit and data
pylab.clf()
pylab.plot(xdata,ydata,'o')
pylab.plot(x,y)
# Plots the confidence band as shaded area
pylab.fill_between(xcb, lcb, ucb, alpha=0.3, facecolor='gray')
pylab.show()
pylab.draw()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment