Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@

## Unreleased

- Weighted `linear` fits now show a confidence-interval band by default (previously they drew only the fitted line), by fitting via `GLM.glm` which supports confidence intervals for weighted models. `linear` gained the following keywords:

- `weighttype`: The `StatsBase.AbstractWeights` type used for the `weights` mapping). Currently only supports `:fweights` until GLM.jl v2 is released.
- `distr` and `link`: Forwarded to `GLM.glm` for weighted fits.

[#710](https://github.com/MakieOrg/AlgebraOfGraphics.jl/pull/710)

## v0.13.2 - 2026-09-03

- Mappings with `verbatim` no longer pick up another layer's scale for the same aesthetic [#786](https://github.com/MakieOrg/AlgebraOfGraphics.jl/pull/786).
Expand Down
2 changes: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ DataAPI = "1"
Dictionaries = "0.3, 0.4"
DynamicQuantities = "1"
FileIO = "1.1"
GLM = "1.9.1"
GLM = "1.9.2"
GeoInterface = "1"
GeometryBasics = "0.4.1, 0.5"
GridLayoutBase = "0.6, 0.7, 0.8, 0.9, 0.10, 0.11"
Expand Down
25 changes: 25 additions & 0 deletions docs/src/reference/analyses.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,31 @@ specs = data(df) * mapping(:x, :y, color=:a => nonnumeric) * (
draw(specs)
```

Weighted fits are supported via the `weights` keyword of `mapping`. When weights are present, the fit is computed with `GLM.glm`, which also provides a confidence-interval band for weighted models. The weights are interpreted as frequency weights (`StatsBase.fweights`), meaning the effective sample size is the sum of the weights. When weighting by measurement uncertainties (inverse-variance weights), normalize the weights to sum to the number of data points so that the confidence band reflects the true sample size rather than `sum(weights)`:

```@example analyses
using Random
Random.seed!(111)
colors = Makie.wong_colors()
df = let
x = 1:5
y_err = randn(length(x))
y = x .+ y_err
y_unc = abs.(y_err)
# Inverse-variance weights, normalized to sum to the number of data points
w = inv.(y_unc .^ 2)
weights = w .* (length(w) / sum(w))
(; x, y, y_unc, weights)
end
specs = data(df) * mapping(:x, :y) * (
(visual(Scatter) + mapping(:y_unc) * visual(Errorbars)) * visual(; label = "data") +
mapping(; weights = :weights) * linear() * visual(; color = colors[1], label = "weighted fit")
)
draw(specs)
```

With this normalization, the frequency-weight fit is numerically identical to one using analytic weights. Other weight types (`:aweights`, `:pweights`) will become available via the `weighttype` keyword of [`linear`](@ref) once GLM.jl v2 is released. Note that the usual caveats still apply for working with different kinds of weights. See the [StatsBase.jl documentation](https://juliastats.org/StatsBase.jl/stable/weights/) for more.

## Smoothing

```@docs
Expand Down
39 changes: 34 additions & 5 deletions src/transformations/linear.jl
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ Base.@kwdef struct LinearAnalysis{I}
dropcollinear::Bool = false
interval::I = automatic
level::Float64 = 0.95
weighttype::Symbol = :fweights
distr::GLM.Distribution = GLM.Normal()
link::GLM.Link = GLM.canonicallink(distr)
end

function add_intercept_column(x::AbstractVector{T}) where {T}
Expand All @@ -12,6 +15,17 @@ function add_intercept_column(x::AbstractVector{T}) where {T}
return mat
end

function get_weighttype(s::Symbol)
# GLM v1 treats all weights as frequency weights, so allowing `:aweights` or
# `:pweights` here would silently compute `:fweights` statistics.
# TODO: Support `:aweights` and `:pweights` once GLM v2 is released
# https://github.com/JuliaStats/GLM.jl/pull/487
if s !== :fweights
throw(ArgumentError("Invalid `weighttype = $(repr(s))`. Currently only `:fweights` is supported, as GLM.jl v1 treats all weights as frequency weights. `:aweights` and `:pweights` will become available with GLM.jl v2."))
end
return StatsBase.fweights
end

# TODO: add multidimensional version
function (l::LinearAnalysis)(input::ProcessedLayer)
tx = position_transform(input.axis_transforms, Lines, input.attributes, 2, 1)
Expand All @@ -23,11 +37,15 @@ function (l::LinearAnalysis)(input::ProcessedLayer)
xn = to_transformed_numerical(x, tx)
yn = to_transformed_numerical(y, ty)
weights_raw = get(n, :weights, similar(xn, 0))
weights = StatsBase.fweights(to_unitless_numerical(weights_raw))
default_interval = length(weights) > 0 ? nothing : :confidence
interval = l.interval === automatic ? default_interval : l.interval
weights = get_weighttype(l.weighttype)(to_unitless_numerical(weights_raw))
interval = l.interval === automatic ? :confidence : l.interval
# FIXME: handle collinear case gracefully
lin_model = GLM.lm(add_intercept_column(xn), yn; weights, l.dropcollinear)
lin_model = if isempty(weights)
GLM.lm(add_intercept_column(xn), yn; l.dropcollinear)
else
# Supports confidence intervals, while `GLM.lm` currently does not
GLM.glm(add_intercept_column(xn), yn, l.distr, l.link; weights, l.dropcollinear)
end
x̂n = collect(range(extrema(xn)..., length = l.npoints))
pred = GLM.predict(lin_model, add_intercept_column(x̂n); interval, l.level)
x̂ = from_transformed_numerical(x̂n, x, tx)
Expand Down Expand Up @@ -61,7 +79,7 @@ function (l::LinearAnalysis)(input::ProcessedLayer)
end

"""
linear(; interval=automatic, level=0.95, dropcollinear=false, npoints=200)
linear(; interval = automatic, level = 0.95, dropcollinear = false, npoints = 200, weighttype = :fweights, distr = GLM.Normal(), link = GLM.canonicallink(distr))

Compute a linear fit of `y ~ 1 + x`. An optional named mapping `weights` determines the weights.
Use `interval` to specify what type of interval the shaded band should represent,
Expand All @@ -74,6 +92,17 @@ it is possible to set `dropcollinear=true`.
`npoints` is the number of points used by Makie to draw the shaded band.

Weighted data is supported via the keyword `weights` (passed to `mapping`).
Weighted fits are computed with `GLM.glm` (which supports confidence intervals,
while weighted `GLM.lm` currently does not) and default to showing a `:confidence` band;
`interval = :prediction` is not available for weighted fits.
Additional weight support is provided via the `weighttype`, `distr`, and `link` keywords.
`weighttype` specifies the `StatsBase.AbstractWeights` type used to interpret the weights
(currently only `:fweights`, until GLM.jl v2 is released).
Since frequency weights treat `sum(weights)` as the effective sample size,
inverse-variance weights should be normalized to sum to the number of data points
so that the confidence band reflects the true sample size.
`distr` and `link` are forwarded to `GLM.glm`.
See the GLM.jl documentation for more on working with weighted data.

Rows with `missing` or `NaN` in any numeric input are dropped; `Inf`/`-Inf` errors.

Expand Down
27 changes: 23 additions & 4 deletions test/analyses.jl
Original file line number Diff line number Diff line change
Expand Up @@ -535,26 +535,35 @@ end
x1 = df.x[df.c .== "a"]
y1 = df.y[df.c .== "a"]
z1 = fweights(df.z[df.c .== "a"])
lm1 = GLM.lm([fill(one(eltype(x1)), length(x1)) x1], y1; dropcollinear, weights = z1)
glm1 = GLM.glm([fill(one(eltype(x1)), length(x1)) x1], y1, GLM.Normal(), GLM.IdentityLink(); weights = z1, dropcollinear)
x̂1 = range(extrema(x1)...; length = npoints)
ŷ1 = vec(GLM.predict(lm1, [ones(length(x̂1)) x̂1]; interval = nothing))
ŷ1, lower1, upper1 = map(vec, GLM.predict(glm1, [ones(length(x̂1)) x̂1]; interval = :confidence))

x2 = df.x[df.c .== "b"]
y2 = df.y[df.c .== "b"]
z2 = fweights(df.z[df.c .== "b"])
lm2 = GLM.lm([fill(one(eltype(x2)), length(x2)) x2], y2; dropcollinear, weights = z2)
glm2 = GLM.glm([fill(one(eltype(x2)), length(x2)) x2], y2, GLM.Normal(), GLM.IdentityLink(); weights = z2, dropcollinear)
x̂2 = range(extrema(x2)...; length = npoints)
ŷ2 = vec(GLM.predict(lm2, [ones(length(x̂2)) x̂2]; interval = nothing))
ŷ2, lower2, upper2 = map(vec, GLM.predict(glm2, [ones(length(x̂2)) x̂2]; interval = :confidence))

pl_band = processedlayers.layers[1]
pl_line = processedlayers.layers[2]
x̂, ŷ = pl_line.positional
x̂b, lower, upper = pl_band.positional

@test x̂[1] ≈ x̂1
@test ŷ[1] ≈ ŷ1
@test x̂b[1] ≈ x̂1
@test lower[1] ≈ lower1
@test upper[1] ≈ upper1

@test x̂[2] ≈ x̂2
@test ŷ[2] ≈ ŷ2
@test x̂b[2] ≈ x̂2
@test lower[2] ≈ lower2
@test upper[2] ≈ upper2

@test pl_band.plottype == Band

@test pl_line.primary == NamedArguments((color = ["a", "b"],))
@test isempty(pl_line.named)
Expand All @@ -570,6 +579,16 @@ end
@test labels == map(AlgebraOfGraphics.to_label, pl_line.labels)
end

@testset "weightedlinear invalid weighttype" begin
# Only `:fweights` is supported until GLM v2; `:aweights`/`:pweights` would
# silently compute frequency-weight statistics on GLM v1.
df = (x = [1.0, 2.0, 3.0, 4.0], y = [1.0, 1.9, 3.1, 4.0], z = [1, 2, 1, 2])
for weighttype in (:aweights, :pweights, :invalid)
layer = data(df) * mapping(:x, :y, weights = :z) * linear(; weighttype)
@test_throws ArgumentError AlgebraOfGraphics.ProcessedLayers(layer)
end
end

@testset "smooth" begin
df = (x = rand(1000), y = rand(1000), c = rand(["a", "b"], 1000))
npoints = 150
Expand Down
Loading