Search code examples
plotjuliamakie.jl

Link axes in Makie.jl if other plot elements present


I would like to create multiple subplots with their own individual legends and shared y-axis limits. I am currently creating the subplots in a loop by doing the following:

fig = Figure()
    
for i in 1:3
    lines(fig[i, 1], rand(10), label="$i")
end
    
linkyaxes!(fig.content...)
    
fig

This works fine, but when attempting to add a legend to each subplot next:

fig = Figure()
    
for i in 1:3
    lines(fig[i, 1], rand(10), label="$i")
    axislegend()
end
    
linkyaxes!(fig.content...)
    
fig

this now throws an error:

MethodError: Cannot `convert` an object of type Makie.MakieLayout.Legend to an object of type Makie.MakieLayout.Axis

because fig.content now includes Makie.MakieLayout.Legend() objects, in addition to the original Axis objects from before.

Do I need to filter these out beforehand, or is there a better way to produce the desired plots?


Solution

  • I'm not sure this is the best approach, but you could ensure that you pass the axes to linkyaxes! this way:

    axs = []
    
    fig = Figure()
    
    for i in 1:3
        ax = lines(fig[i, 1], rand(10), label="$i").axis
        push!(axs, ax)
        axislegend()
    end
    
    linkyaxes!(axs...)