Plots: string interpolation in labels?

I’m solving a differential equation several times where I vary a parameter, say Kp = linspace(1,5,5). The result is a vector of vectors (time series), say vec is a vector (1D array) of vectors (time series). I then want to plot these plots in the same plot window. If t is the time vector, I then want to plot:

plot(t,vec)

However, I’d also like to insert the values of K as labels in the plots. In essence:

plot(t,vec,label=["Kp = $(Kp[1])" "Kp = $(Kp[2])" ....]

where $ is supposed to indicate string interpolation.

Problem 1: will this work? (I haven’t been able to make it work yet…)
Problem 2: will it work with the LaTeXString package? I like to use LaTeX syntax, i.e.:

L"$K_p = $ $(Kp[1])"

where the first pair of symbols $ bracket the LaTeX math expression, while the third time symbol $ appears, it is meant as string interpolation…

Problem 3: is it even possible to use string interpolation within the LaTeX $ brackets??

Sorry if the explanation is convoluted.

Problem 1: will this work?

Yes, you can interpolate in labels. Labels are just ordinary strings and you can construct them using any valid Julia code.

Your example code has spaces rather than commas separating list items, which is maybe why it wasn’t working for you?

It won’t work with L"..." strings because those treat $ as literal dollar signs, not as interpolation. But you can make an LaTeX equation with an ordinary string as long as you are willing to put \ before dollar signs and backslashes, e.g. "\$K_p = $(Kp[1])\$".

1 Like

Thanks. I guess the reason why I didn’t use commas between label elements is that I assumed it is the same rules for these as for, e.g., colors, etc. For colors, I need to do:

plot(x,[y1,y2], lc = [:blue :red])

so I assumed the same was true for labels…

Update: for some time now, LaTeXStrings has supported Julia interpolation with %$, e.g. L"K_p = %$(Kp[1])"

3 Likes