Home > OS >  LaTeX in plot titles using a loop
LaTeX in plot titles using a loop

Time:02-20

I just learned how to insert (a limited number of) LaTeX expressions into my plot titles with expression(<LaTeX code>). How can I generate plots containing LaTeX in their titles using a loop? For example, say I have:

par(mfrow = c(2,2))

x <- seq(1,10,0.1)
y <- sin(x)

plot(x, y, main = expression(sigma[1]))
plot(x, y, main = expression(sigma[2]))

This produces the desired output: enter image description here

How can I achieve the same output, but by replacing the last two lines with a loop? I tried

par(mfrow = c(2,2))
for (i in 1:2){
    plot(x, y, main = expression(sigma[i]))
}

but the i was not interpreted as a variable: enter image description here

Any solutions for this?

CodePudding user response:

We can use bquote instead of expression. This allows partial unquoting, meaning you can substitute the value of i inside the expression by wrapping it like this: .(i)

par(mfrow = c(2,2))

x <- seq(1,10,0.1)
y <- sin(x)

for(i in 1:4) plot(x, y, main = bquote(paste("My plot for ", sigma[.(i)], " :")))

Created on 2022-02-19 by the enter image description here

  • Related