Legend tweaking

Source code

using AlgebraOfGraphics, CairoMakie

To tweak the position and appearance of the legend, simply use the legend keyword when plotting. For example

labels = ["a looooooong label", "an even loooooonger label", "and one more long label"]
df = (x=rand(100), y=rand(100), group=rand(labels, 100))
layers = linear() + mapping(color=:group)
plt = data(df) * layers * mapping(:x, :y)
fg = draw(plt, legend=(position=:top, titleposition=:left, framevisible=true, padding=5))

To adjust the title and order of labels in a legend you can use the pair syntax.

layers = linear() +  mapping(color=:group => sorter(labels) => "Labels")
plt = data(df) * layers * mapping(:x, :y)

Adding a plot to a pre-existing figure with draw! will not draw the legend automatically. In this case, one must use legend! and specify the axis to which it should be added.

The tellheight = false, tellwidth = false arguments are useful to avoid changing the dimensions of the axis.

makie_fig = Figure()
ax_scatter = Axis(makie_fig[1, 1])

grid = draw!(ax_scatter, plt)

legend!(makie_fig[1, 1], grid; tellheight=false, tellwidth=false, halign=:right, valign=:top)


This page was generated using DemoCards.jl and Literate.jl.