【问题标题】:Add an htmlwidget from R to a PowerPoint Slide将 R 中的 htmlwidget 添加到 PowerPoint 幻灯片
【发布时间】:2017-08-11 05:09:49
【问题描述】:

如何将来自 DiagrammeR::grViz() 的 htmlwidget 图表输出添加到 PowerPoint 幻灯片中?我更喜欢保留矢量图形并尽量减少手动操作。

下面main.R 中的代码将DOT 图很好地呈现为htmlwidget

# ./code/digraph-test.dot 
digraph my_plot_name {
A->B->C;
}

# main.R
library(DiagrammeR)
digraph_test <- grViz("./code/digraph-test.dot")

我想将此输出添加到 PowerPoint 幻灯片中。我从this post 改编了以下代码。

library( ReporteRs )
require( ggplot2 )
mydoc = pptx( )
mydoc = addSlide( mydoc, slide.layout = "Title and Content" )
mydoc = addTitle( mydoc, "Plot examples" )
myplot = grViz("./code/digraph-test.dot")
# myplot = qplot(Sepal.Length, Petal.Length
#                , data = iris, color = Species
#                , size = Petal.Width, alpha = I(0.7))
mydoc = addPlot( mydoc, function( ) print( myplot ), vector.graphic=TRUE)
writeDoc( mydoc, file = "test plot.pptx" )

它会产生以下错误:

Error in .jcall(slide, "I", "add", dml.object) : 
  javax.xml.bind.UnmarshalException
 - with linked exception:
[org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 2; The markup in the document preceding the root element must be well-formed.]

似乎有些人在LiveWeb add-in for PowerPoint 上取得了成功。我遇到了 ActiveX 问题,只找到了 hack 解决方案,并选择不追究。必须有一个简单的解决方案,对吧?

【问题讨论】:

  • 为什么不使用an RMarkdown slide format
  • @alistaire 我希望我能。不幸的是,我需要将 PowerPoint 幻灯片添加到更长的 PowerPoint 演示文稿中。

标签: r powerpoint graphviz reporters diagrammer


【解决方案1】:

正如@alistaire 所建议的,Rmarkdown 将是此图表的更好解决方案,但如果您在 PowerPoint 中需要它,我建议使用 package webshot 将其作为 png 文件获取。

library(DiagrammeR)
library( ReporteRs )

mydoc = pptx()
mydoc = addSlide( mydoc, slide.layout = "Title and Content" )
mydoc = addTitle( mydoc, "Plot examples" )

# compute new size for image to fit in ppt shape ----
shape_dim <- dim(mydoc)$size
shape_height <- setNames( shape_dim["height"], NULL ) * 72 
shape_width <- setNames( shape_dim["width"], NULL ) * 72

# reuse the shape dimensions in grViz call ----
digraph_test <- grViz("digraph-test.dot", width = shape_width, height = shape_height )
htmlwidgets::saveWidget(widget = digraph_test, file = "digraph.html", selfcontained = TRUE)
webshot::webshot(url = "digraph.html", selector = '.html-widget-static-bound', file= "digraph.png")


mydoc = addImage( mydoc, filename = "digraph.png" )
writeDoc( mydoc, file = "test plot.pptx" )

【讨论】:

  • 大卫,你为什么选择 500x300?我尝试调整您的代码以使图表填充完整的 PowerPoint 幻灯片(使用自定义的整页内容幻灯片布局模板)。我发现 960x540 完美地填充了该幻灯片。但是结果图偏离了中心。知道发生了什么吗?
  • 我已经更新了示例,使其适应 ppt 形状的大小 - 我认为最好控制大小
  • 这对我来说非常有效(我根据this post调整了您的代码以填充完整的 PowerPoint 幻灯片)。项目完全居中。超级好用!
  • 谢谢你,大卫。我知道这可能对我很无知但是......!如果我想使用您精彩的ggiraph 创建一个带有弹出窗口的交互式 ggplot,有没有办法在保留交互性的同时将该交互性导入 PowerPoint? (我已经尝试了上述方法,但它并没有显示弹出窗口。)再次道歉,如果这是无知和真诚的感谢 ggiraph。
  • 顺便说一句,如果您希望我将此作为单独的问题添加,请说出来
猜你喜欢
  • 1970-01-01
  • 2015-07-26
  • 1970-01-01
  • 1970-01-01
  • 2022-09-26
  • 2022-10-02
  • 2021-01-21
  • 2015-07-27
  • 1970-01-01
相关资源
最近更新 更多