如何保存/导出SunburstR包生成的HTML可视化部件?
如何导出自定义后的sunburst HTML Widget
我需要将自定义后的sunburst HTML widget保存/导出,以便分享给他人,以下是我的代码和示例数据集:
示例数据集
df <- read.csv(system.file("examples/visit-sequences.csv",package="sunburstR"),header = FALSE,stringsAsFactors = FALSE)[1:100,]
自定义sunburst widget代码
sun <- sunburst(df, percent=TRUE,count=TRUE, legend = list(w=150), withD3 = T, width = "100%", height = 400) htmlwidgets::onRender( sun, " function(el, x) { d3.selectAll('.sunburst-legend text').attr('font-size', '10px'); d3.select(el).select('.sunburst-togglelegend').property('checked',true); // force show the legend, check legend d3.select(el).select('.sunburst-togglelegend').on('click')(); // simulate click d3.select(el).select('.sunburst-togglelegend').remove() // remove the legend toggle } " )
导出方法
方法1:导出为独立HTML文件
使用htmlwidgets::saveWidget()函数直接导出为可分享的HTML文件,代码如下:
htmlwidgets::saveWidget(sun, file = "sunburst_export.html", selfcontained = TRUE)
参数说明:
selfcontained = TRUE:将所有依赖资源(CSS、JS脚本等)打包进单个HTML文件,接收方直接打开即可查看,无需额外文件;若设为FALSE,会生成一个包含主HTML文件和依赖文件夹的目录。file:自定义保存的文件路径及名称,可根据需求修改。
方法2:导出为静态图片(如PNG/PDF)
如果需要静态图片格式,可借助webshot包将HTML转为图片:
# 先安装依赖包 install.packages("webshot") webshot::install_phantomjs() # 将导出的HTML转为PNG图片 webshot::webshot("sunburst_export.html", "sunburst_export.png")
内容的提问来源于stack exchange,提问作者user2845095
相关产品推荐
相关产品推荐

