【问题标题】:R: save ggplot2 plots in different excel sheetsR:将ggplot2图保存在不同的excel表中
【发布时间】:2020-07-27 18:59:35
【问题描述】:

我正在使用 R 包 ggplot2 创建不同组的图。然后,我想将这些图导出到具有不同工作表的 excel 文件中。我使用了以下代码:

List1 <- split(df, df$Group) #Split data frame by group
ListGraphs <- lapply(List1, function(x) ggplot(x, aes(x=Quintiles, y=Perc, group=Answer, color=as.factor(Answer)))+
              geom_line(size=2)
              theme(legend.title=element_blank(), legend.position="bottom", legend.key = element_blank())) #Create a plot for each element of the list
wb <- createWorkbook() #Create an Excel workbook 
for (s in seq_along(ListGraphs)){
name <- addWorksheet(wb,names(ListGraphs[s])) #Add worksheets with group names
insertPlot(wb, name)} #insert plots in the excel sheets
saveWorkbook(wb,"a.xlsx", overwrite = TRUE) #Save workbook 

但是,这不起作用。我有一个包含多张工作表的 excel 文件,并且每张都有相同的情节。我认为问题在于当我将图保存在列表中时,因为它创建了一个列表列表。但我不知道我应该在这里改变什么。谁能帮帮我?

这是我的数据框(df)的示例:

  Quintiles Group    Answer   Perc
1 1          1       1        96 
2 1          1       4        4 
3 1          2       4        4 
4 2          2       5        96 
5 2          3       1        64 
6 3          3       2        8 
7 3          3       3        28

【问题讨论】:

    标签: r ggplot2 openxlsx


    【解决方案1】:

    insertPlot 的帮助下:当前绘图 使用 dev.copy 保存到临时图像文件中。然后使用 insertImage 将该文件写入工作簿
    这意味着您需要在每个 insertPlot 之前打印第 k 个图。

    library(openxlsx)
    # A test data set
    set.seed(1)
    n <- 1000
    df <- data.frame(Perc=runif(n), Quintiles=runif(n), 
                     Answer=sample(1:2, size=n, replace=T), 
                     Group =sample(1:5, size=n, replace=T))
    
    List1 <- split(df, df$Group) 
    ListGraphs <- lapply(List1, function(x) {
         ggplot(x, aes(x=Quintiles, y=Perc, group=Answer, color=as.factor(Answer))) +
         geom_line(size=2) +
         theme(legend.title=element_blank(), legend.position="bottom", 
               legend.key = element_blank())
    }) 
    wb <- createWorkbook() 
    for (k in seq_along(ListGraphs)) {
      name <- addWorksheet(wb, names(ListGraphs)[k]) 
      plot(ListGraphs[[k]])   # Plot the k-th graph before insertPlot
      insertPlot(wb, sheet=name)                     
    } 
    saveWorkbook(wb,"a.xlsx", overwrite = TRUE) 
    

    【讨论】:

      猜你喜欢
      • 2012-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-01
      • 2018-02-14
      • 1970-01-01
      • 2017-01-17
      • 1970-01-01
      相关资源
      最近更新 更多