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
XY
1113
225
3318
4416
5525
6617
7720
8824
9923
101022
...
100100209

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.6
DataFrames 1.5.0
GLM 1.8.3

To run this tutorial locally, download this file and open it with Pluto.jl.