Skip to content

Commit

Permalink
Legend overrides (#570)
Browse files Browse the repository at this point in the history
Uses changes in Makie 0.21.13 to allow overriding legend element
attributes via a `legend` keyword:

```julia
df = (;
    x = randn(200) .+ repeat([0, 3], 100),
    y = randn(200) .+ repeat([0, 3], 100),
    group = repeat(["A", "B"], 100)
)

spec = data(df) *
    mapping(:x, :y, color = :group) *
    visual(Scatter; markersize = 5, legend = (; markersize = 15))

draw(spec)
```

<img width="584" alt="image"
src="https://github.com/user-attachments/assets/a31593c7-92a0-43a6-af18-c350ad97d827">
  • Loading branch information
jkrumbiegel authored Oct 7, 2024
1 parent 3db46be commit 448d330
Show file tree
Hide file tree
Showing 8 changed files with 78 additions and 5 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## Unreleased

## v0.8.12 - 2024-10-07

- Added `legend` keyword in `visual` to allow overriding legend element attributes [#570](https://github.com/MakieOrg/AlgebraOfGraphics.jl/pull/570).

## v0.8.11 - 2024-09-25

- Fixed lexicographic natural sorting of tuples (this would fall back to default sort order before) [#568](https://github.com/MakieOrg/AlgebraOfGraphics.jl/pull/568).
Expand Down
4 changes: 2 additions & 2 deletions Project.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
name = "AlgebraOfGraphics"
uuid = "cbdf2221-f076-402e-a563-3d30da359d67"
authors = ["Pietro Vertechi", "Julius Krumbiegel"]
version = "0.8.11"
version = "0.8.12"

[deps]
Accessors = "7d9f7c33-5ae7-4f3b-8dc6-eff91059b697"
Expand Down Expand Up @@ -39,7 +39,7 @@ GridLayoutBase = "0.6, 0.7, 0.8, 0.9, 0.10, 0.11"
Isoband = "0.1"
KernelDensity = "0.6"
Loess = "0.5.1, 0.6.1"
Makie = "0.20.1, 0.21.2"
Makie = "0.21.13"
NaturalSort = "1"
PlotUtils = "1"
PolygonOps = "0.1.1"
Expand Down
18 changes: 18 additions & 0 deletions docs/gallery/gallery/customization/legend.jl
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,21 @@ grid = draw!(ax_scatter, plt)
legend!(makie_fig[1, 1], grid; tellheight=false, tellwidth=false, halign=:right, valign=:top)

makie_fig

# If the automatic legend elements are not legible enough, you can change their properties
# by passing overrides to the `legend` attribute of a `visual`.

df = (;
x = repeat(1:100, 5),
y = reduce(vcat, [[cos(x) for x in range(0, 8pi, length = 100)] .+ 0.3 .* randn.() for _ in 1:5]),
group = repeat(1:5, inner = 100),
)

lin = data(df) *
mapping(:x, :y, group = :group => nonnumeric) *
visual(Lines, linewidth = 0.3, label = "Lines", legend = (; linewidth = 1.5))
sca = data(df) *
mapping(:x, :y => y -> y + 5, group = :group => nonnumeric) *
visual(Scatter, markersize = 3, label = "Scatter", legend = (; markersize = 12))

draw(lin + sca)
31 changes: 31 additions & 0 deletions docs/src/generated/visual.jl
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,34 @@ legend!(f[1, 2], fg)
legend!(f[1, 3], fg, order = [:Label, :Color])

f

# ## Legend element overrides

# Sometimes it might be necessary to override legend element properties that are otherwise
# copied from the `visual` settings. For example, a scatter plot with many small markers might have
# a legend that is hard to read. We can use AlgebraOfGraphics's `legend` keyword in `visual` to
# specify override attributes via key-value pairs. Here we increase the markersize for the `MarkerElement`s
# that are created for a `Scatter` plot:

df = (;
x = randn(200) .+ repeat([0, 3], 100),
y = randn(200) .+ repeat([0, 3], 100),
group = repeat(["A", "B"], 100)
)

spec = data(df) *
mapping(:x, :y, color = :group) *
visual(Scatter; markersize = 5, legend = (; markersize = 15))

draw(spec)

# These are the attributes you can override (note that some of them have convenience aliases like `color` which applies to all elements while `polycolor` only applies to `PolyElement`s):
#
# - `MarkerElement`
# - `[marker]points`, `markersize`, `[marker]strokewidth`, `[marker]color`, `[marker]strokecolor`, `[marker]colorrange`, `[marker]colormap`
# - `LineElement`
# - `[line]points`, `linewidth`, `[line]color`, `linestyle`, `[line]colorrange`, `[line]colormap`
# - `PolyElement`
# - `[poly]points`, `[poly]strokewidth`, `[poly]color`, `[poly]strokecolor`, `[poly]colorrange`, `[poly]colormap`
#
# More information about legend overrides can be found in [Makie's documentation](https://docs.makie.org/stable/reference/blocks/legend#Overriding-legend-entry-attributes).
2 changes: 1 addition & 1 deletion src/algebra/layers.jl
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ end
function to_entry(p::ProcessedLayer, categoricalscales::Dictionary, continuousscales::Dictionary)
entry = to_entry(p.plottype, p, categoricalscales, continuousscales)
insert!(entry.named, :cycle, nothing)
for key in (:group, :layout, :row, :col, :dodge_x, :dodge_y)
for key in (:group, :layout, :row, :col, :dodge_x, :dodge_y, :legend)
if haskey(entry.named, key)
delete!(entry.named, key)
end
Expand Down
18 changes: 16 additions & 2 deletions src/guides/legend.jl
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ function compute_legend(grid::Matrix{AxisEntries}; order::Union{Nothing,Abstract
push!(used_scales, :Label)
for (label, processedlayers) in pairs(labelled_layers)
push!(legend_els, mapreduce(vcat, processedlayers) do p
legend_elements(p, MixedArguments())
_legend_elements(p, MixedArguments())
end)
push!(datalabs, label)
end
Expand Down Expand Up @@ -275,7 +275,7 @@ function compute_legend(grid::Matrix{AxisEntries}; order::Union{Nothing,Abstract
# skip the legend element for this processed layer if the kwargs are empty
# which means that no scale in this merge group affected this processedlayer
if !isempty(kwargs)
append!(_legend_els[i], legend_elements(processedlayer, kwargs))
append!(_legend_els[i], _legend_elements(processedlayer, kwargs))
end
end
end
Expand Down Expand Up @@ -306,6 +306,20 @@ function datavalues_plotvalues_datalabels(aes::Type{AesMarkerSize}, scale::Conti
datavalues, markersizes, string.(datavalues)
end

function _legend_elements(processedlayer, scale_args::MixedArguments)
els = legend_elements(processedlayer, scale_args)
if haskey(processedlayer.attributes, :legend)
# LegendOverride and apply_legend_override are not public API (introduced in 0.21.13)
# but unlikely to change much so it's easier to just depend on them instead of copying
# their implementation
override = Makie.LegendOverride(processedlayer.attributes[:legend])
for el in els
Makie.apply_legend_override!(el, override)
end
end
return els
end

function legend_elements(p::ProcessedLayer, scale_args::MixedArguments)
legend_elements(p.plottype, p.attributes, scale_args)
end
Expand Down
6 changes: 6 additions & 0 deletions test/reference_tests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1001,3 +1001,9 @@ reftest("scatterlines legend") do
spec2 = data((; x = 1:10, y = cos.(1:10) .+ 2)) * mapping(:x, :y) * visual(ScatterLines, color = :blue, markercolor = :cyan, label = "markercolor cyan")
draw(spec1 + spec2)
end

reftest("legend element overrides") do
spec = mapping(1:10, 1:10, color = repeat(["A", "B"], inner = 5)) *
visual(Scatter, legend = (; markersize = 30))
draw(spec)
end
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

2 comments on commit 448d330

@jkrumbiegel
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@JuliaRegistrator
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Registration pull request created: JuliaRegistries/General/116747

Tip: Release Notes

Did you know you can add release notes too? Just add markdown formatted text underneath the comment after the text
"Release notes:" and it will be added to the registry PR, and if TagBot is installed it will also be added to the
release that TagBot creates. i.e.

@JuliaRegistrator register

Release notes:

## Breaking changes

- blah

To add them here just re-invoke and the PR will be updated.

Tagging

After the above pull request is merged, it is recommended that a tag is created on this repository for the registered package version.

This will be done automatically if the Julia TagBot GitHub Action is installed, or can be done manually through the github interface, or via:

git tag -a v0.8.12 -m "<description of version>" 448d330c242bc6d33cf9c4cbe5d77f24a760d6ed
git push origin v0.8.12

Please sign in to comment.