# Weighted linear regression with confidence interval fitted to error bars

**URL:** <https://discourse.julialang.org/t/weighted-linear-regression-with-confidence-interval-fitted-to-error-bars/60743>\
**Category:** General Usage\
**Tags:** statistics, regression, fit, glm\
**Created:** [May 7, 2021, 9:10pm UTC](https://discourse.julialang.org/t/weighted-linear-regression-with-confidence-interval-fitted-to-error-bars/60743 "2021-05-07T21:10:36Z")\
**Posts on this page:** 1\
**Showing post:** 6

<div class="post-metadata">

**Author:** ![rafael.guerra](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rafael.guerra/32/216610_2.png) [@rafael.guerra](https://discourse.julialang.org/u/rafael.guerra)\
**Post date:** [May 8, 2021, 10:12pm UTC](https://discourse.julialang.org/t/weighted-linear-regression-with-confidence-interval-fitted-to-error-bars/60743/6 "2021-05-08T22:12:52Z")

</div>

As indicated in GLM.jl’s doc above, `glm` does not handle inverse-variance weighting.

For this purpose, you may use LsqFit.jl.

```julia
using DataFrames, LsqFit, Printf, Plots; gr()

df = DataFrame(x = [0.0, 0.0669873, 0.25, 0.5, 0.75, 0.933013, 1.0],
        y = [0.223, 0.291, 0.393, 0.549, 0.73, 0.85, 0.896],
        u_y = [0.023, 0.024, 0.027, 0.031, 0.037, 0.041, 0.043])

x, y = df.x, df.y
wt = 1 ./ df.u_y .^2

p0 = [0.5, 0.5]
m(x, p) = p[1] .+ p[2] * x # p: model parameters
fit = curve_fit(m, x, y, wt, p0)

cf = coef(fit)
ci = confidence_interval(fit, 0.05) # 5% significance level

str = @sprintf("Y = (%.2f +/- %.2f) + (%.2f +/- %.2f)*X",
          cf[1],diff([ci[1]...])[1]/2, cf[2],diff([ci[2]...])[1]/2)

tl, bl = ci[1][1] .+ ci[2][2]*x, ci[1][2] .+ ci[2][1]*x
σp, σm = maximum([tl bl], dims=2) .- m(x,cf), m(x,cf) .- minimum([tl bl], dims=2)

plot(x, cf[1] .+ cf[2]*x, color=:lightblue, ribbon=(σp,σm), label=str)
plot!(x, cf[1] .+ cf[2]*x, color=:blues, lw=1, label=false, xlabel="X",ylabel="Y")
scatter!(x,y, ms=3,label=false,mc=:blue, yerror=df.u_y, legend=:topleft)

```

![LsqFit_weighted_linear_regression](https://global.discourse-cdn.com/julialang/original/3X/0/3/038fd8ca3b5ce5d8581108966b05d1d97c8cdb03.png)

---

_[View the full topic](https://discourse.julialang.org/t/weighted-linear-regression-with-confidence-interval-fitted-to-error-bars/60743)._
