title: Programmatically insert header and plot in same code chunk with R markdown using results='asis'
body: <p>The <code>results = 'asis'</code> chunk option within Rmarkdown allows one to easily dynamically create text including headers.  However, I wish to dynamically create a header with the <code>asis</code> option, but then in the same code chunk insert some graphics.</p>
  
  <p>The most related answer I could find for this is here: <a href="https://stackoverflow.com/questions/26588350/programmatically-insert-text-headers-and-lists-with-r-markdown">Programmatically insert text, headers and lists with R markdown</a>, but the answer to this question does not allow both dynamic headers and plots within those dynamic headers.</p>
  
  <p>Here is a simple reproducible example follows demonstrating what I can and cannot achieve with <code>results = 'asis'</code></p>
  
  <p>The code directly below does what I would expect, creating a header for each Species.</p>
  
  <pre><code>---
  output: html_document
  ---
  ```{r echo = FALSE, results ='asis'}
  for(Species in levels(iris$Species)){
    cat('#', Species, '\n')
  }
  ```
  </code></pre>
  
  <p>The code directly below here does not do what I would like.  Ideally, the code directly below would generate a header for each Species with a plot underneath each header.  Instead, it generates the single <code>setosa</code> header in the output file followed by the three plots.</p>
  
  <pre><code>---
  output: html_document
  ---
  ```{r echo = FALSE, results ='asis'}
  library(ggplot2)
  for(Species in levels(iris$Species)){
    cat('#', Species, '\n')
    p &lt;- ggplot(iris[iris$Species == Species,], aes(x = Sepal.Length, y = Sepal.Width)) +
      geom_point()
    print(p)
  }
  ```
  </code></pre>
  
  <p>Is there some way to dynamically generate the 3 headers with a plot under each header?</p>