# Math In Plots.jl

could someone please show me how to set a simple equation into a plot, say \sqrt{\frac{a}{b}} ?

julia> using Plots, LaTeXStrings

julia> x = rand(10); y = rand(10);

julia> s = L"\sqrt{\frac{a}{b}}";

julia> ann = [(x[i],y[i],s) for i ∈ 1:10];

julia> scatter(x, y, title = s, label = s, xaxis = s, yaxis = s, annotations = ann)

5 Likes

Hi Sleort,

That’s very useful. I have a follow up question. what if a and b are some parameters values and I am running a loop over a and b to plot many graphs which I would be happy to put the value of a and b on graph. Could we do that in Julia?

Best,
Ethan

Do you mean something like this:

using Plots, LaTeXStrings, Printf

makenicenumberstring(n) = Printf.@sprintf("%.2f", n)
a = rand(10)
b = rand(10)
astr = makenicenumberstring.(a)
bstr = makenicenumberstring.(b)

x = rand(10)
y = rand(10)

s = L"\sqrt{\frac{a}{b}}"
sab = map(ab -> latexstring("\\sqrt{\\frac{$(ab[1])}{$(ab[2])}}"), zip(astr, bstr))
ann = tuple.(x,y,sab)

scatter(x, y, title = s, label = s, xaxis = s, yaxis = s, annotations = ann)


? (See the documentation of LaTeXStrings.jl for why you need to use latexstring instead of just L.)

However, if you care about beauty (e.g. for publication), I would suggest that you have a look at PGFPlotsX.jl as well…

2 Likes

yes! that’s it! very cool! thanks!

Plots can write to a pgfplots backend as well, so you can get exactly the same end results. The big difference is the syntax used to create the plots. PGFPlotsX tries to be as close to the original pgfplots syntax as possible. Plots tries to abstract that as well and hide differences between plotting backends.

Sure, but can you access “lower level functionality” (like TikZ) by using Plots?

No, you get much more control by using pgfplots(x) directly. So my remark was only on the notion that pgfplotsx created inherently more beautiful results.

Fair enough.

Hmm… yeah, I can see that I should have been more explicit on what I had in mind. What I meant to say was that if ethanminfang would like to do something like this (or beyond), it may be better to use (something like) PGFPlotsX.

One way to think about PGFPlotsX is as a DSL that allows you to interpolate representations of various Julia objects into LaTeX code.

The disadvantage is that you don’t get the nice, generic, mostly backend-independent syntax of Plots.jl.

The advantage is that porting pgfplots examples found online or in the manual is very easy.

haha. No, actually. I just want to put the parameter values on the plot so I gets to know them if I have too many plots (like hundreds)

If you only want to put parameter values on the plot – and don’t need the Latex typesetting – this is easier:

using Plots, Printf

a = rand(10)
b = rand(10)
x = rand(10)
y = rand(10)

sab = [@sprintf("(%.2f, %.2f)", ab...) for ab ∈ zip(a,b)]
ann = tuple.(x, y, sab)
scatter(x, y, annotations = ann)

2 Likes