Linear model fitting
This is an example tutorial showing how to fit a linear model with GLM.jl and plot it with Makie.jl.
Let's start by generating the linear relationship
$$y = 2x + \epsilon,$$
where $\epsilon$ is random noise.
using DataFrames
df = let
X = 1:100
Y = [2x + rand(1:20) for x in X]
DataFrame(; X, Y)
end
X | Y | |
---|---|---|
1 | 1 | 13 |
2 | 2 | 5 |
3 | 3 | 18 |
4 | 4 | 16 |
5 | 5 | 25 |
6 | 6 | 17 |
7 | 7 | 20 |
8 | 8 | 24 |
9 | 9 | 23 |
10 | 10 | 22 |
... | ||
100 | 100 | 209 |
In a plot, the data looks as follows:
using CairoMakie
lines(df.X, df.Y)
On this data, a linear model can be fitted:
using GLM
model = lm(@formula(Y ~ X), df);
Which gives estimates for the intercept and slope:
intercept, slope = GLM.coef(model)
2-element Vector{Float64}: 8.313939393939519 2.0270507050705047
With this, we can determine all values which are "predicted" by the fitted model:
Y_fitted = [intercept + slope * x for x in df.X];
And plot it again:
let
fig = Figure()
ax = Axis(fig[1, 1])
lines!(ax, df.X, df.Y, label="true")
lines!(ax, df.X, Y_fitted; color=:black, linestyle=:dash, label="fitted")
axislegend(ax; position=:lt)
fig
end
Built with Julia 1.9.1 and
CairoMakie 0.10.6DataFrames 1.5.0
GLM 1.8.3
To run this tutorial locally, download this file and open it with Pluto.jl.