Search code examples
rlatexknitrsweave

I have a for loop of qplots, how can you structure the plots individually using LaTeX code e.g adding captions to the plots


\begin{figure}[h]
\centering

<<echo=FALSE>>=

for(i in 2:38){
print(my_plot_function(i))
}

@

\end{figure}

This is my code, but what is happening is that when I compile my PDF I only get the first two plots that fit on the first page and I do not get the rest of the plots. I would like to have all of the plots on separate pages.

And how would I go about adding captions to each individual plot in the for loop.


Solution

  • \documentclass{article}
    \begin{document}
    
    <<echo = FALSE, fig.cap = c("First, Second, Third"), results = "asis">>=
      library(ggplot2)
      for (i in 1:3) {
        print(qplot(x = 1, y = i))
        cat("Arbitrary \\LaTeX code! \\clearpage")
      }
    @
      
    \end{document}
    

    You can use the chunk option fig.cap to add captions to your plots. Note that this will wrap your figure in a figure environment, turning it into a float.

    Use the chunk option results="asis" to be able to print arbitrary text (including LaTeX markup) into your document using cat().