Plot two legends (e.g. one for color and one for shape) with `Plots.jl`

How can I make a plot like this in Plots.jl (this was made with matplotlib):

image

Basically four lines:

plot( data1, color=c1, linestyle=s1)
plot!(data2, color=c2, linestyle=s1)
plot!(data3, color=c1, linestyle=s2)
plot!(data4, color=c2, linestyle=s2)

And now I would like one legend that explains the linestyle and one that explains the color. Is that feasible directly through Plots.jl?

Not sure about the second legend (I guess in matplotlib this operates directly with legend objects?), but you could simply add two invisible lines to the plot to have the legend entries:

plot(rand(10), color=1, label = "random")
plot!(rand(10), color=2, label = "optimized")
plot!(rand(10), color=1, linestyle=:dot, label = "")
plot!(rand(10), color=2, linestyle=:dot, label = "")
plot!([1], [0], label = "validation", color = "black")
plot!([1], [0], linestyle = :dot, label = "cost", color = "black")
5 Likes

Indeed, the matplotlib code operates on legend objects and series handles directly.

The invisible lines suggestion would work great, thanks!

The solution proposed here is quick and elegant, but in my workflow I will be plotting clouds of points (PCA kind of plot)

I care about how two different variables cluster together, so one variable determines the colour and a different variable determines markershape. I work with several datasets, so the amount of colours/shapes I use will vary a lot.

It would be nice to have the option to add a different legend for each of these things (linetype, markershape, markersize, linecolour, markercolour…)

Has there been any update on this since this post was first solved?

Also - is there any backend that is especially good for legend manipulation? I tend to use PlotlyJS because I love the interactivity of the plot, but I find I lack some wanted freedom with my legends in general (e.g. exact position, or number of columns in legend). Any comments appreciated! Thanks

If you need that level of control the answer is probably to just use Makie, where you can build any legend you want.

1 Like

Thanks! I’ll have a look at it