How to store r ggplot graph as html code snippet

前端 未结 3 1388
你的背包
你的背包 2021-02-10 01:52

I am creating an html document by creating various objects with ggplotly() and htmltools functions like h3() and html(). Then I submit th

3条回答
  •  礼貌的吻别
    2021-02-10 02:35

    I ended up generating a temparory image file, then base64 encoding it, within a function I called encodeGraphic() (borrowing code from LukeA's post):

    library(ggplot2)
    library(RCurl)
    library(htmltools)
    encodeGraphic <- function(g) {
      png(tf1 <- tempfile(fileext = ".png"))  # Get an unused filename in the session's temporary directory, and open that file for .png structured output.
      print(g)  # Output a graphic to the file
      dev.off()  # Close the file.
      txt <- RCurl::base64Encode(readBin(tf1, "raw", file.info(tf1)[1, "size"]), "txt")  # Convert the graphic image to a base 64 encoded string.
      myImage <- htmltools::HTML(sprintf('', txt))  # Save the image as a markdown-friendly html object.
      return(myImage)
    }
    
    HTMLOut <- "~/TEST.html"   # Say where to save the html file.
    g <- ggplot(mtcars, aes(x=gear,y=mpg,group=factor(am),color=factor(am))) + geom_line()  # Create some ggplot graph object
    hg <- encodeGraphic(g)  # run the function that base64 encodes the graph
    forHTML <- list(h1("My header"), p("Lead-in text about the graph"), hg)
    save_html(forHTML, HTMLOut)  # output it to the html file.
    

提交回复
热议问题