Variable in legends



I’m trying to add legends using Latex as follows:

using PyPlot

m = 100
xx = collect(linspace(-1.0, 1.0, 100))
yy = sin(m*xx)
zz = collect(linspace(-5, 3.0, 100))


h1, h2 = plot(xx, yy, "b.", xx, zz, "r+")
legend((h1, h2), (L"$\sin( $m x)$", L"Linear"))

I’m trying to print the value of m in the legend, but don’t know how to and can’t find any examples. Could anyone give me a hint?


I don’t think you need the outside “$”?


It doesn’t work. I believe the outside “$” must not be absent. Thanks a lot though. Any other hints?


If you use L"..." to make a LaTeX string, then you can’t use $ interpolation in the strings. (Technically, $ interpolation doesn’t occur in Julia string macros.) This is intentional, because $ has its own meaning in LaTeX.

To do interpolation, just use an ordinary Julia string. This means you have to escape characters like $ and \ if you want to use them for LaTeX.

legend((h1, h2), ("\$\\sin( $m x)\$", "Linear"))

(Note also that you wouldn’t want to use L"Linear" for a text label like Linear, because L"..." implicitly puts the contents into an equation.)


Ah, I see! Thanks a lot! Now everything is right for me.


Another option:

latexstring("\$\\sin(" * string(m) * "x)\$")


Thanks for the comments! It’s always good to know an alternative. Can you remind me what is * for?


It combines two normal strings.

x = "Hello"
y = "World"
z = x * " " * y # First string, a space, and the second string
"Hello World"

See *(s,t)

Edit: Added a documentation link


Thanks a lot!! I remember now.