Annotated unitful axis in Plots

I’m plotting a function, which accepts a unitful argument. Now, if I want to add an x axis label

p = plot!(;xlabel="particle radius")

I get an error:

ERROR: DimensionError:  and μm are not dimensionally compatible.

Sure, I can redefine my function for a unitless input, but is there a more elegant solution? What is happening here?

Use xlabel!. Your approach adds another subplot which is probably not what you want. This is not true, at least on a current version (1.39.0) and both command work the same as noted by @rafael.guerra below.

@Eben60 Which version of Plots are you running?

1 Like

For me, plot!(;xlabel="x") is the same as xlabel!("x")", both work without error. However, in both cases the x-axis units are lost and not appended to the label.

PS:
Unitful v1.17.0, Plots v1.39.0

1 Like

This works, x-axis labeled as particle radius (µm)

p=nothing
firstrun = true
for freq in (2:2:14) .* u"MHz"
    global firstrun, p
    prel(r) = Prel(r, freq, σ)
    xlim = (5u"µm", 100u"µm")
    if firstrun
        plot(prel; xlim, label="$freq", xlabel="particle radius")
    else
        p= plot!(prel; xlim, label="$freq")
    end
    firstrun = false
end
p = plot!(;ylabel="a.u.")
display(p)

and this errors:

p=nothing
firstrun = true
for freq in (2:2:14) .* u"MHz"
    global firstrun, p
    prel(r) = Prel(r, freq, σ)
    xlim = (5u"µm", 100u"µm")
    if firstrun
        plot(prel; xlim, label="$freq")
    else
        p= plot!(prel; xlim, label="$freq")
    end
    firstrun = false
end
p = plot!(;ylabel="a.u.", xlabel="particle radius")
display(p)

and this errors either:

xlabel!("particle radius")
p = plot!(;ylabel="a.u.")
display(p)

Unitful v1.17.0, Plots v1.39.0 (updated from 1.15 and 1.38)

I have filed an issue with Plots.

1 Like