Plot legend with multiple columns

Hello, is there a way to split the labels in the legend in two columns using Plots.jl?
I know how to do it using PyPlot (just use legend(ncol=2)) but I would like to avoid using python, if possible.

Thank you very much for your help!

Not really with Plots.jl, but with GRUtils.jl, you might achieve this:

using GRUtils
y = sin.((0:0.1:2pi) .+ [0 0.5pi pi 1.5pi])
plot(y)
legend("\\phi = 0", "\\phi = 0.5\\pi", "\\phi = \\pi", "\\phi = 1.5\\pi",
    maxrows = 2)

Notice that:

  • This feature is in the master branch, but not yet released, so in the meantime you should ]add GRUtils#master.
  • This is not yet very well documented – work in progress…
  • GRUtils does not use Python, but you’ll need the GR plotting library instead. Nevertheless, if you have been using Plots you’ll probably have it already installed; and if not, it should be installed and built with GRUtils via its dependency GR.jl, normally without having to do anything.
  • With the keyword argument maxrows you are not telling how many columns you want in the legend, but the maximum number of rows allowed in each column of the legend (so the number of columns depends on that and the number of geometries you have labelled).
1 Like

I hit this too. I’m wondering if there is a solution to this in Plots.jl now?

I don’t think so, or at least I would have expected the solution to be referenced here (which tracks this amongst other issues): Legends meta-issue · Issue #2423 · JuliaPlots/Plots.jl · GitHub

(Congrats on your prize btw!)

Thanks!

I guess I’ll check out other solutions then

So, any solution for Plots.jl?

@kongdd, one workaround is to use insets, but example would definitely require more plumbing:

using Plots; gr()

# define n-curves and n-labels
n = 7
x = 0:0.1:6π
yk = [k*sin.(x .- k) .* exp.(-0.02*k*x) for k in 1:n]
labels = " k = " .* string.(1:n) .* " "

# plot n-curves and legend with n-labels over 2 columns
ncolors =  distinguishable_colors(n, [RGB(0,1,1), RGB(0,0,0)], dropseed=false)
n2 = ceil(Int,n/2)
b = 0.15  # adjust this function of legend sizes
p = plot(x,yk, xlabel="x", ylabel="y", color=ncolors', legend=false, widen=false)
plot!(p, (1:n2)', color=ncolors[1:n2]', inset=(1, bbox(1-2*b,0,b,1,:left)), bg=:transparent,
      subplot=2, legendfontsize=10, border=:none, label = permutedims(labels[1:n2]),
      bg_legend=:white, fg_legend=nothing, axes=false)
plot!(p, (n2+1:n)', color=ncolors[n2+1:n]', inset=(1, bbox(1-b,0, b,1,:left)), bg=:transparent,
      subplot=3, legendfontsize=10, border=:none, label = permutedims(labels[n2+1:n]),
      bg_legend=:white, fg_legend=nothing, axes=false)

Plot_gr_insets_for_legends_in_2_columns

1 Like