Reputation: 745
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:
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:
Any solutions for this?
Upvotes: 5
Views: 273
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"))
Upvotes: 1
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
Upvotes: 3
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
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)]))
}
Upvotes: 4