在PowerPoint中创建多个可编辑的GGPlot

creating multiple editable ggplots in powerpoint

提问人:confusedindividual 提问时间:11/16/2023 最后编辑:Philconfusedindividual 更新时间:11/16/2023 访问量:30

问:

我正在尝试创建一种方法来获取 ggplots 列表并将它们转换为 powerpoint,每张幻灯片都是列表中可编辑的 ggplot。下面我提供了我拥有的代码,并在注释中解释了问题发生的位置,即在循环期间。似乎它在循环时会覆盖自己。

```
library(dplyr)
library(tidyverse)
library(officer)
library(rvg)
```
#create example data 
```
df <- data.frame(country = c(rep('USA',20), rep('Canada',20), rep('Mexico',20)),

                 wave = c(1:20, 1:20, 1:20),

                 par = c(1:20 + 5*runif(20), 21:40 + 10*runif(20), 1:20 + 15*runif(20)))

 

countries <- unique(df$country)

 ```

#make list of plots 
```
plot_list <- list()

i <- 1

 

for (c in countries){

  pl <- ggplot(data = df %>% filter(country == c)) +

    geom_point(aes(wave, par), size = 3, color = 'red') +

    labs(title = as.character(c), x = 'wave', y = 'value') +

    theme_bw(base_size = 16)

 

  plot_list[[i]] <- pl

  i <- i + 1

}

#plot_list is the list of plots 
plot_list

 

#convert list of plots into editable vector graphic objects

myplots <-  dml(ggobj = plot_list

                ,bg = "white"

                ,pointsize = 12

                ,editable = TRUE)
 

### now create loop ---- this is were I get issues. it seems like the plots are just overriding one another during the loop and not creating a new slide

{

  for(plot in 1:length(plot_list)) {

    doc <- read_pptx()

    doc <- add_slide(doc, "Title and Content", "Office Theme")

    doc <- ph_with(doc, plot_list[[plot]], location = ph_location_fullsize())

    fileout <- "vectorGraphics.pptx"

    print(doc, target = fileout)

  }

}

 ```
R 循环 PowerPoint

评论

1赞 I_O 11/16/2023
取出和退出循环(否则,您将重新初始化每个循环周期)。read_pptx()print(doc, ...)doc

答:

2赞 Friede 11/16/2023 #1

调整循环:

doc <- read_pptx()
for(plot in 1:length(plot_list)) {
  doc <- add_slide(doc, "Title and Content", "Office Theme")
  doc <- ph_with(doc, plot_list[[plot]], location = ph_location_fullsize())
}
fileout <- "vectorGraphics.pptx"
print(doc, target = fileout)

根据您删除的评论:只需将一些行移到循环之外即可。

2赞 stefan 11/16/2023 #2

首先,我建议用它来创建您的地块列表。其次,要将绘图转换为对象,您必须遍历绘图列表。最后,如果您希望在单独的幻灯片上放置一个 pptx,请在循环之外创建并导出 pptx:lapplydmlfor

library(ggplot2)
library(officer)
library(rvg)

plot_list <- df |>
  split(~country) |>
  lapply(\(x) {
    ggplot(x) +
      geom_point(aes(wave, par), size = 3, color = "red") +
      labs(title = unique(x$country), x = "wave", y = "value") +
      theme_bw(base_size = 16)
  })

plot_list_dml <- lapply(
  plot_list, \(x)
  dml(
    ggobj = x,
    bg = "white",
    pointsize = 12,
    editable = TRUE
  )
)

doc <- read_pptx()
for (plot in plot_list_dml) {
  doc <- add_slide(doc, "Title and Content", "Office Theme")

  doc <- ph_with(doc, plot, location = ph_location_fullsize())
}

fileout <- "vectorGraphics.pptx"

print(doc, target = fileout)

enter image description here