Legend in Makie

Hi, I’m looking how to add a legend to a plot in Makie. While there’s an exported function AbstractPlotting.legend, there’s no documentation and apparently no mention of it in any example in the docs.

Example:

> p= lines(0:0.1:10,rand(101), label="1")
> scatter!(p,rand(0:10,10),rand(10),label="2")
> legend!(p)  # this doesn't work

I also tried something more that doesn’t work, inspired by https://github.com/JuliaPlots/Makie.jl/issues/61#issuecomment-437918488

> lgd= Makie.legend(p, ["1","2"], camera=campixel!, raw=true)

Is your use-case not covered by colorlegend?

Edit: No, I suppose it doesn’t. What are you trying to do with the label kwarg? I don’t see it listed as an available attribute, and looking at the source code, that’s never a kwarg that’s looked for afaict.

Edit2: In any case, here’s how I got your example to work:

using Makie

p= lines(0:0.1:10,rand(101), label="1")
scatter!(p,rand(0:10,10),rand(10),label="2")
lgd = legend([p[2], p[end]], ["1", "2"]; camera=campixel!, raw=true)
vbox(p, lgd)
2 Likes

This works, thanks a lot! Maybe it’s worth adding such an example to the gallery? I’m touching Makie for the first time now, so I’m not too confident adding that myself.

Maybe it’s worth adding such an example to the gallery?

There is an example, and you found it… You just ignored, that you need to pass the legend labels AND the plots to it :wink:

Of course, bad error messages for wrong arguments are to blame here, but not really sure how another example would improve that situation.

1 Like

Indeed you’re right and thanks for pointing this out. It’s not sure others will find it there though or in the github issue where I did. Maybe it would help if it were on Makie’s docs as well.

It kind of is, since the MakieGallery, where you can find this, is right on the first page of the docs.
I admit, right now it’s not that easy to find, though. It should get a better title + I should put legend/ colorlegend in the tag search.

1 Like

Ah, if the page search doesn’t look in the code, that explains it. Thanks in any case!