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

use*_*203 4 r ggplot2 htmltools

我通过使用ggplotly()和htmltools函数(例如h3()和)创建各种对象来创建html文档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.
Run Code Online (Sandbox Code Playgroud)

我想用仅以不会在save_html函数中引起错误的方式呈现g7的内容替换plotly对象(p7)。

我曾希望找到一个可以直接对Base64编码 ggplot对象进行编码的函数,但看来我首先需要将“ ggplot”对象输出为.png文件(或SVG,根据下面的Teng L所述),然后进行base64编码它。我希望有一种更直接的方法,但是我可能最终会这样做,例如/sf/answers/2338753651/,以

g7img <- "<img src=\"data:image/png;base64,(base64encode string)\""
g7img <- htmltools::html(g7img)
Run Code Online (Sandbox Code Playgroud)

use*_*203 6

我最终生成了一个临时图像文件,然后在我调用的函数中对其进行 base64 编码encodeGraphic()(从LukeA 的帖子中借用代码):

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.
Run Code Online (Sandbox Code Playgroud)


Mau*_*ers 5

如果要将图另存为动态plotly图,可以使用htmlwidgets::saveWidget。这将产生一个独立的html文件。

这是一个最小的示例:

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");
Run Code Online (Sandbox Code Playgroud)