0

我正在使用库(ReporteRs)将我的图表导出到 Power Point。

library(ggplot2)
library(grid)
library(gridExtra)
library(ReporteRs)

# Creation of pptx object (default template)
mydoc <- pptx( )
mydoc <- addSlide( mydoc, "Title and Content" )

#data frame
df <- data.frame(
  "Year" = c(2011,2012,2012,2012,2012,2013,2013,2013,2013,2014,2014,2014,2014,2015,2015,2015,2015,2016,2016,2016,2016,2017,2017,2017),
  "Quarter" = c(4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4,1,2,3),
  "Value" = c(9.930561,6.768615,5.030881,3.638038,4.186386,8.490943,9.806658,8.922669,6.880410,8.679514,2.897544,3.666259,5.930273,3.601645,7.160027,5.785060,7.496486,4.808837,4.929674,0.812019,4.239284,5.288036,5.402848,11.062810)
                )

#graph
dfg <- ggplot(data = df, aes(x = interaction(Year, Quarter, lex.order = TRUE),y = Value, group = 1)) +
  geom_line(colour = gr1,size=1) +
  coord_cartesian(ylim = c(0, 12), expand = FALSE) +
  scale_y_continuous(breaks=seq(0, 12, by=2),position = "right") +
  annotate(geom = "text", x = 0.5+seq(1:(length(df$Quarter)-1)), y = -0.5, label = rep(1:4, len = length(df$Quarter)-1), size = 3) +
  annotate(geom = "text", x =  4* (1:(length(unique(df$Year))-1))-1, y = -1.5, label = ((min(df$Year)+1):max(df$Year)), size = 4)+
  theme_classic() +
  theme(plot.margin = unit(c(1, 1, 2, 1), "lines"),
        axis.title.x = element_blank(),
        axis.text.x = element_blank(),
        legend.title = element_blank(),
        legend.background =element_rect(fill = "white"),
        legend.position="top",
        panel.background = element_rect( color = "#E2E2E2"),
        axis.title.y = element_blank(),
        axis.line.x = element_line(color="black", size = 0.75),
        axis.line.y = element_line(color="#E2E2E2"),
        axis.ticks.y = element_blank(),
        axis.ticks.length = unit(.8, "cm"),
        panel.grid.major = element_line(colour = "#E2E2E2"))

# making certain x axis ticks long 
for (i in 0:(length(unique(df$Year))-2)) {
  dfg = dfg + annotation_custom(grob = linesGrob(gp=gpar(col= "black")),  
                                      ymin = -0, 
                                      ymax =-2, 
                                      xmin = 4*i+1, 
                                      xmax = 4*i+1)
}

# remove clipping of x axis labels
dfg1 <- ggplot_gtable(ggplot_build(dfg))
dfg1$layout$clip[dfg1$layout$name == "panel"] <- "off"
dfg2 <- grid.draw(dfg1)


# add a plot into mydoc 
mydoc <- addPlot(mydoc,print,x=dfg2)

# write mydoc 
writeDoc( mydoc, "example.pptx" )

#######################

但是,尽管我可以在 R 中看到图表 [在此处输入图像描述][1],但 ReporteRs 无法发布“dfg2”。

我收到以下错误:

Error in .jcall(slide, "I", "add", dml.object) : 
  javax.xml.bind.UnmarshalException

因为“dfg2”返回 NULL。

如何将“grid.draw()”图表发布到我的 .pptx 中?

谢谢你。

4

1 回答 1

0

grid.draw打开图形设备并绘制绘图。print是为ggplot对象。您需要通过以下方式更改脚本的结尾:

# dfg2 <- grid.draw(dfg1)

# add a plot into mydoc 
mydoc <- addPlot(mydoc,grid.draw,x=dfg1)
于 2018-03-13T09:21:33.003 回答