【发布时间】:2021-12-17 08:31:39
【问题描述】:
我正在通过使用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.
我想将 plotly 对象 (p7) 替换为仅以不导致 save_html 函数出错的方式呈现 g7 的东西。
我曾希望找到一个可以直接 Base64 编码 ggplot 对象的函数,但似乎我首先需要将“ggplot”对象输出为 .png 文件(或 SVG,根据Teng L,下),然后对其进行 base64 编码。我希望有一种更直接的方法,但我最终可能会这样做,就像在 https://stackoverflow.com/a/33410766/3799203 中一样,以
结尾g7img <- "<img src=\"data:image/png;base64,(base64encode string)\""
g7img <- htmltools::html(g7img)
【问题讨论】:
-
你看过这个post
-
谢谢,我确实看到了那个帖子。我想避免阴谋,因为它创建的自包含 html 文件很大(超过 2 兆字节),以支持它提供的所有交互功能。