如何将r ggplot图存储为html代码段

时间:2018-05-09 02:33:36

标签: r ggplot2 htmltools

我正在创建一个html文档,方法是使用ggplotly()和htmltools函数创建各种对象,例如h3()html()。然后我将它们作为列表提交给htmltools::save_html()以创建一个html文件。

我想直接添加ggplot图表作为图像,而不是附加所有的情节铃声和口哨声。最后,我将创建一个自包含的html文件(没有依赖项),而剧情的东西会使该文件过大。

是否有某些函数将ggplot对象转换为某个html类型的对象?或者我是否必须将ggplot保存为.png文件,然后将.png文件读入我添加到save_html()函数列表中的某个对象?

我的R代码看起来像这样:

library("tidyverse")
library("plotly")
library("htmltools")

HTMLOut <- "c:/Users/MrMagoo/My.html")
df <- data.frame(x=1:25, y=c(1:25*1:25))

g7 <- ggplot(df,aes(x=x, y=y)) + geom_point()
p7 <- 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 <- h2(id="graph7", "Title for graph #7")
d7 <- 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.

我想用一些不会导致save_html函数出错的方式替换刚出现g7的图形对象(p7)。

我曾希望找到一个可以直接 Base64编码一个ggplot对象的函数,但似乎我首先需要输出'ggplot'对象作为.png文件(或SVG,per Teng L,下面),然后base64编码它。我希望有一种更直接的方式,但我最终可能会这样做,就像在https://stackoverflow.com/a/33410766/3799203中一样,以

结束
g7img <- "<img src=\"data:image/png;base64,(base64encode string)\""
g7img <- htmltools::html(g7img)

3 个答案:

答案 0 :(得分:4)

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");

答案 1 :(得分:1)

我最终在一个名为encodeGraphic()的函数中生成一个临时图像文件,然后对它进行base64编码(从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.

答案 2 :(得分:0)

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.