How to store r ggplot graph as html code snippet

前端 未结 3 1383
你的背包
你的背包 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('<img src="data:image/png;base64,%s">', 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.
    
    0 讨论(0)
  • 2021-02-10 02:40

    I think what you want may be close to one of the following:

    1. Seems you are creating an HTML report but hasn't checked out RMarkdown. It comes with Base64 encode. When you create an RMarkdown report, pandoc automatically converts any plots into an HTML element within the document, so the report is self-contained.

    2. SVG plots. This is less likely to be what you might want, but SVG plots are markup-language based and may be easily portable. Specify .svg extension when you use ggsave() and you should be getting an SVG image. Note that SVG is an as-is implementation of the plot, so if can be huge in file size if you have thousands of shapes and lines.

    0 讨论(0)
  • 2021-02-10 02:49

    If you want to save the plot as a dynamic plotly graph, you could use htmlwidgets::saveWidget. This will produce a stand-alone html file.

    Here is a minimal example:

    library(tidyverse);
    library(plotly);
    library(htmlwidgets);
    
    df <- data.frame(x = 1:25, y = c(1:25 * 1:25))
    gg <- ggplot(df,aes(x = x, y = y)) + geom_point()
    
    # Save ggplotly as widget in file test.html
    saveWidget(ggplotly(gg), file = "test.html");
    
    0 讨论(0)
提交回复
热议问题