2

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?

Ian Weaver
  • 150
  • 9

1 Answers1

2

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...)
Benoit Pasquier
  • 2,868
  • 9
  • 21
  • 1
    Oh, I didn't know about `.axis`, thanks Benoit! – Ian Weaver Jul 09 '21 at 01:51
  • When you invoke a function as `plot_func(::GridPosition, ...)`, it returns an `AxisPlot` which is basically a container for an axis and whichever plot `plot_func` created. For full versatility you can capture both as `ax, plt = lines(...)`. – Anshul Singhvi Mar 12 '23 at 08:32