将R中的htmlwidget添加到PowerPoint幻灯片中

时间:2017-03-20 02:21:13

标签: r powerpoint graphviz reporters diagrammer

如何将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解决方案,并选择了不追求。必须有一个简单的解决方案,对吧?

1 个答案:

答案 0 :(得分:3)

正如@alistaire所建议的那样,Rmarkdown对于这个图表来说是一个更好的解决方案,但是如果你需要在PowerPoint中使用它,我建议使用包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" )