PyPlot: how to include a variable in a title

Hi,

I have this loop in my code:

for i=1:30
    PyPlot.figure(i)
    if i < 3
        PyPlot.plot(y[1:801],eigenfunction_approx[1:801,i])
        PyPlot.title("Plot of the ${i}th eigenfunction")
    elseif i < 10
        PyPlot.plot(y[1:1001],eigenfunction_approx[1:1001,i])
        PyPlot.title("Plot of the ${i}th eigenfunction")
    else
        PyPlot.plot(y[1:1301],eigenfunction_approx[1:1301,i])
        PyPlot.title("Plot of the ${i}th eigenfunction")
    end
end

I’d like the title to include the number of the eigenfunction being displayed, which in this loop is i. How do I do that? The only docs for the Julia PyPlot module I’ve found is its README and it doesn’t mention how one would do this. I’ve tried using PyPlot.title("Plot of the ", i, "th eigenfunction") as I thought maybe it might work like Python does and I’d expect something like that to work in Python. If you’d like the error I got from that it’s:

PyError ($(Expr(:escape, :(ccall(#= /home/fusion809/.julia/packages/PyCall/zqDXB/src/pyfncall.jl:43 =# @pysym(:PyObject_Call), PyPtr, (PyPtr, PyPtr, PyPtr), o, pyargsptr, kw))))) <class 'ValueError'>
ValueError("'th eigenfunction' is not a valid value for loc; supported values are 'left', 'center', 'right'")
  File "/usr/lib/python3.8/site-packages/matplotlib/pyplot.py", line 3031, in title
    return gca().set_title(
  File "/usr/lib/python3.8/site-packages/matplotlib/axes/_axes.py", line 198, in set_title
    title = cbook._check_getitem(titles, loc=loc.lower())
  File "/usr/lib/python3.8/site-packages/matplotlib/cbook/__init__.py", line 2165, in _check_getitem
    raise ValueError(

and from my loop above I got:

syntax: invalid interpolation syntax: "${"

I’m just hoping one of you good folks knows the answer to this problem.

Thanks for your time

You want PyPlot.title("Plot of the $(i)th eigenfunction").

This has nothing to do with PyPlot specifically. This is how you do string interpolation in Julia.

3 Likes