在powerpoint中创建多个可编辑的ggplots

问题描述 投票:0回答:2

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

library(dplyr)
library(tidyverse)
library(officer)
library(rvg)

#创建示例数据

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)

#制作地块列表

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 loops rstudio powerpoint
2个回答
1
投票

首先,我建议使用

lapply
创建绘图列表。其次,要将绘图转换为
dml
对象,您必须循环遍历绘图列表。最后,如果您想要一个 pptx,每个图都在单独的幻灯片上,请在
for
循环之外创建并导出该 pptx:

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)


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)

我已将

fileout <- "vectorGraphics.pptx"
更改为
fileout <- paste0("vectorGraphics", plot, ".pptx")
。这允许每次循环迭代将对象
doc
存储到不同的文件名中。您的代码每次迭代都会覆盖存储在“vectorGraphics.pptx”下的文件。

© www.soinside.com 2019 - 2024. All rights reserved.