Leonidas
Leonidas

Reputation: 745

LaTeX in plot titles using a loop

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?

Upvotes: 5

Views: 273

Answers (4)

Mikael Jagan
Mikael Jagan

Reputation: 11326

For your reference, there is also tikzDevice, which actually generates .tex:

sigma <- 2^(1:4)
x <- seq(0, 2 * pi, 0.01 * pi)

tikzDevice::tikz("sine.tex", standAlone = TRUE)
par(mfrow = c(2L, 2L))
for (i in seq_along(sigma)) {
    y <- sin(sigma[i] * x)
    plot(x, y, type = "o", xlab = "$x$", ylab = "$y$", 
         main = sprintf("$y = \\sin(\\sigma_{%d} x)$", i))
}
dev.off()
tools::texi2dvi("sine.tex", pdf = TRUE)
system(paste(getOption("pdfviewer"), "sine.pdf"))

enter image description here

Upvotes: 1

akrun
akrun

Reputation: 887183

Another option is substitute

for (i in 1:2){
     plot(x, y, main = substitute(paste("My plot for ", sigma[i]), list(i = i)))
 }

-output

enter image description here

Upvotes: 3

Allan Cameron
Allan Cameron

Reputation: 173858

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 reprex package (v2.0.1)

Upvotes: 4

TarJae
TarJae

Reputation: 78937

par(mfrow = c(2,2))
loop.vector <- 1:2

for (i in loop.vector) {
  x <- seq(1,10,0.1)
  y <- sin(x)
  plot(x, y, main = bquote(sigma[.(i)]))
}

enter image description here

Upvotes: 4

Related Questions