UniftulRecipes and LaTeXStrings

Hi

Is there a way to use simultaneously UnitfulRecipes and LaTeXStrings? Somewhat like (adapted from UniftulRecipes’ first example:

using Unitful, UnitfulRecipes, Plots, LaTeXStrings
const a = 1u"m/s^2"
v(t) = a * t
x(t) = a/2 * t^2
t = (0:0.01:100)*u"s"
plot(x.(t), v.(t), xlabel=L"\textrm{Position} \xi", ylabel=L"\textrm{Speed} \sigma")

and it should have the correct LaTeX labels in both axes, appended with their respective units (within parentheses). However, this does not work… I might always ustrip the unitful quantities and set the labels manually together with their units, but I thought this should work seamlessly with Unitful, UnitfulRecipes and LaTeXStrings…

That’s because the appending was expecting a String not an AbstractString.

I just made a PR to UnitfulRecipes to fix this, but I think there is a road block with your specific example. First, I think that using \textrm is a problem because one would then also want to use \textrm to append the label for consistency, but UnitfulRecipes does not know about LaTeXStrings or any LaTeX commands, so, instead I think it’s better to use $ signs, e.g.,

julia> xlabel = L"Position $\xi$"
L"Position $\xi$"

which can then be nicely modified by appending " (m)":

julia> LaTeXString(xlabel * " (m)")
L"Position $\xi$ (m)"

However, the GR backend does not work nicely with that syntax for some reason (gentle ping to @jheinen who will certainly know more about that). Anyway, the PR should work as long as you use, e.g., the pyplot() backend, as shown in the example commented in the PR and copied here for your convenience:

using Unitful, UnitfulRecipes, Plots, LaTeXStrings # Note it's UnitfulRecipes PR #35 here
pyplot() # does not work with the GR backend for me (yet?)
const a = 1u"m/s^2"
v(t) = a * t
x(t) = a/2 * t^2
t = (0:0.01:100)*u"s"
plot(x.(t), v.(t), xlabel=L"Position $\xi$", ylabel=L"Speed $\sigma$")

which gives

Hopefully this helps!

1 Like

@briochemc: thanks for the prompt reply and the pull request (PR) filing! I use to use the default GR backend, but I would not mind using the good old pyplot one (very powerful and triggers some good memories from my Matplotlib experience). I hope the PR is easy to implement!

1 Like

No worries! FWIW, I’m the same, I use the default backend (GR) most of the time, especially for quick exploration/plotting, and I generally don’t bother with LaTeX and try to use Unicode instead, which is why I overlooked this LaTeXStrings application, and also never stumbled upon the GR issue with things like plot(rand(10), xlabel=L"my equation is $y = a x + b$").

BTW I think the PR is mostly done, it’s not much more than changing a String into an AbstractString, really. So probably a few days to fix whatever comes up during CI and we’ll merge it! :smiley: