Variable in legends

plotting
pyplot

#1

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))

figure(1)
clf()

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?


#2

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


#3

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


#4

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.)


#5

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


#6

Another option:

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


#7

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


#8

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


#9

Thanks a lot!! I remember now.