我通过创建各种对象使用ggplotly()
和htmltools函数,如h3()
和html()
创建一个html文档。然后,我将它们作为列表提交给htmltools::save_html()
来创建一个html文件。
我希望直接将ggplot图表添加为图片,而不是附加所有的plotly功能。最终,我将创建一个独立的html文件(没有依赖项),而plotly的东西会使该文件过大。
是否有一些函数可以将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。
我曾希望找到一个函数可以直接对ggplot对象进行Base64编码,但似乎我需要先将'ggplot'对象输出为.png文件(或SVG,根据Teng L的建议),然后再进行base64编码。虽然我希望有更直接的方法,但最终可能会采取这种方法,就像https://dev59.com/X1wX5IYBdhLWcg3wwx1S#33410766中所示,最后以...结尾。
g7img <- "<img src=\"data:image/png;base64,(base64encode string)\""
g7img <- htmltools::html(g7img)