Wednesday, December 14, 2011

Calculating and plotting confidence bands for linear regression models

This method calculates the confidence band of an arbitrary linear regression model at a given confidence level in Python. Using this method you can get plots like this:
where the shaded area corresponds to the 2sigma confidence band of the linear fit shown in green. A script illustrating how to use the confband method below is available.

If you use it, let me know if you find any bugs.

Note: the scatterfit method called below is available here.




7 comments:

  1. Hello,
    thank you for the code.
    However they might be two issues :
    sd from scatterfit is already a square root, then it should be :
    dy=q*sd*numpy.sqrt((1./n + sx/sxd) )
    and in (1./n + sx/sxd) should be replaced by (1+ 1./n + sx/sxd). (1./n + sx/sxd) is used for the confidence interval of the regression coefficients not of the data.

    Cheers,
    Vincent.

    ReplyDelete
    Replies
    1. Dear Vincent,
      Thanks for finding those bugs. I fixed the bug and will post the correct version asap!

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
  3. I am interested in what you have done, but I do not see any code or description of the math involved in calculating these confidence bands?

    ReplyDelete
    Replies
    1. Dear Thoger,
      Thanks for pointing that out! For some reason the source code is not showing up anymore in the blog. Probably the blogger admins updated the engine and messed up the source code display.

      I am planning to upload to github the source code involved in the example above very soon. Stay tuned.

      Delete
  4. I would like to know how do you get the plot? I have x and y variables which I have scatter plotted using matplotlib

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete