Display lines handle with variable color inside legend in Makie

using CairoMakie

fig = Figure(resolution=(600,400))
ax = Axis(fig[1, 1])

xs = 0:0.01:10
ys = 0.5 .* sin.(xs)

lines!(ax, xs, ys, label="uniform color")
lines!(ax, xs, ys .+ 1, color=ys.^2, label="variable color")
axislegend(ax)

fig

Is it possible to show a colored line with the color gradient for the line handle inside the legend? Right now it is shown as a black line, which doesn’t match the color of the top line.

There’s no quick builtin way to do this, because usually varying colors are combined with a Colorbar.
You can just pass multiple points and colors to a LineElement because it just passes those to the underlying lines call without checking if they’re scalar, but you can’t set the colormap that way:

f, ax, li = lines(range(0, 10, 100), sin, color = 1:100)
le = LineElement(
    points = Point2f.(range(0, 1, 10), 0.5 .+ 0.5 * sin.(range(0, 2pi, 10))),
    color = 1:10,
)
Legend(f[1, 2], [le], ["hi"])
f

To change the colormap, you currently either have to make your own LineElement-like type where that is possible or reach into the internals. This code can break at any time:

f, ax, li = lines(range(0, 10, 100), sin, color = 1:100, colormap = :inferno)
le = LineElement(
    points = Point2f.(range(0, 1, 10), 0.5 .+ 0.5 * sin.(range(0, 2pi, 10))),
    color = 1:10,
)
l = Legend(f[1, 2], [le], ["hi"])
l.blockscene.children[1].plots[2].colormap = :inferno
f