title: R Markdown: plots within a loop going out of margin when typesetting to PDF
body: <p>When typesetting an R Markdown document to PDF, if a function draws multiple plots, those plots often appear side-by-side, with only the first plot fully within the margins of the page.</p>
  
  <p>Minimal R Markdown example:</p>
  
  <pre><code>---
  title: "Example re plotting problem"
  author: "Daniel E. Weeks"
  date: "May 3, 2016"
  output: pdf_document
  ---
  
  ```{r setup, include=FALSE}
  knitr::opts_chunk$set(echo = TRUE)
  ```
  
  ## Multiple plots within a loop
  
  
  ```{r}
  plots &lt;- function() {
    plot(rnorm(100))
    hist(rnorm(100))
  }
  
  for (i in 1:3) {
   plots()
  }
  ```
  </code></pre>
  
  <p>Here is a screenshot of page 2 of the generated PDF</p>
  
  <p><img src="https://i.stack.imgur.com/8MHGN.png" alt=""></p>
  
  <p>which shows the problem.  I have searched online, but haven't yet found a solution to this problem.</p>
  
  <p>Thank you.</p>
  
  <hr>
  
  <p>The plot hook solution proposed by user2554330 is simple and works well. So this code draws all the plots within the margins of the resulting PDF:</p>
  
  <pre><code>---
  title: "Example re plotting problem"
  author: "Daniel E. Weeks"
  date: "May 3, 2016"
  output: pdf_document
  ---
  
  ```{r setup, include=FALSE}
  knitr::opts_chunk$set(echo = TRUE)
  ```
  
  ## Multiple plots within a loop
  
  
  ```{r}
  plots &lt;- function() {
    plot(rnorm(100))
    hist(rnorm(100))
  }
  ```
  
  ## Call plotting function
  
  ```{r}
  my_plot_hook &lt;- function(x, options)
   paste("\n", knitr::hook_plot_tex(x, options), "\n")
   knitr::knit_hooks$set(plot = my_plot_hook)
  for (i in 1:3) {
  plots()
  }
  ```
  </code></pre>