Plots.jl Align legend labels, :right not working


I am getting familiar with the Plots recipes ecosystem, and I just wrote my first recipe but the attribute “legendfonthalign” does not seem to work. Does anyone know how to do it?

Here is a MWE

@recipe function f(g::CVEpdfPlot)
    legend --> false
    legendfonthalign := :right # this should work!!! right?
    grid := false
    linewidth := 1
    linestyle := :solid

    @series begin
        seriestype := :density

And when I call that plot (with some extra features, like the rainbow color) I get this,with the legend text aligned to the :left ,

what maybe happening?

Thank you

Does it work when you pass it explicitly like plot(my_cve_object, legendfonthalign = :right)?

Also which backend are you using? Note that legendfonthalign is only supported by GR and PGFPlotsX according to the docs.

That said, just doing plot(rand(10, 10), legendfonthalign = :right) doesn’t seem to do anything for me even with the GR backend, so maybe this isn’t the way to use the attribute, or there’s a bug somewhere in Plots…

1 Like

No success either with legendfonthalign attribute.

A workaround is to left-pad the labels beforehand and use a font such as Courier so that the columns of characters are consistently aligned.
Computer Modern legends are not perfectly aligned but look better:

using LaTeXStrings, Plots; gr()

default(fontfamily="Computer Modern")
n = 3:2:23
x = 0:0.01:1; y = [3*n*exp.(-(n*(x .- 0.6)).^4) for n in n];
labels= permutedims(string.(n) .* " [s]")
n = maximum(length.(labels))
plot(x, y, label=lpad.(labels,n), legend=:outertopright)   # legendfont=font(6,"Courier")

Legend with Courier font:

Legend with Computer Modern font:

1 Like

@nilshg @rafael.guerra I appreciate your help guys.

I am using gr() actually, and the lpad solution seems to be good enough at this point. I can save it as a SVG and then align it by hand. Obviously a Plots.jl solution would be ideal.

Thank you!

1 Like