title: How to store r ggplot graph as html code snippet
body: <p>I am creating an html document by creating various objects with <code>ggplotly()</code> and htmltools functions like <code>h3()</code> and <code>html()</code>.  Then I submit them as a list to <code>htmltools::save_html()</code> to create an html file.</p>
  
  <p>I would like to add ggplot charts directly as images, rather than attaching all the plotly bells and whistles. In the end, I will create a self-contained html file (no dependencies), and the plotly stuff would make that file excessively large.</p>
  
  <p>Is there some function that converts a ggplot object into some html-type object?  Or do I have to save the ggplot as a .png file, then read the .png file into some object that I add to the list in the save_html() function?</p>
  
  <p>My R code looks something like this:</p>
  
  <pre><code>library("tidyverse")
  library("plotly")
  library("htmltools")
  
  HTMLOut &lt;- "c:/Users/MrMagoo/My.html")
  df &lt;- data.frame(x=1:25, y=c(1:25*1:25))
  
  g7 &lt;- ggplot(df,aes(x=x, y=y)) + geom_point()
  p7 &lt;- ggplotly(g7)  # I would like to use something other than ggplotly here. Just capturing the ggplot as an image would be fine.
  
  # create other objects to add to the html file
  t7 &lt;- h2(id="graph7", "Title for graph #7")
  d7 &lt;- p("description of graph 7")
  
  save_html(list(t7, p7, d7), HTMLOut)
  # of course, the real code has many more objects in that list – more graphs, text, tables, etc.
  </code></pre>
  
  <p>I would like to replace the plotly object (p7) with something that just presents g7 in a way that would not cause an error in the save_html function.</p>
  
  <p>I had hoped to find a function that could directly <strong>Base64 encode</strong> a ggplot object, but it seems that I first need to output the 'ggplot' object as a .png file (or SVG, per Teng L, below), then base64-encode it.  I was hoping there was a more direct way, but I may end up doing that, as in <a href="https://stackoverflow.com/a/33410766/3799203">https://stackoverflow.com/a/33410766/3799203</a> , ending it with</p>
  
  <pre><code>g7img &lt;- "&lt;img src=\"data:image/png;base64,(base64encode string)\""
  g7img &lt;- htmltools::html(g7img)
  </code></pre>