首页 > 解决方案 > R:将ggplot2图保存在不同的excel表中

问题描述

我正在使用 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

标签: rggplot2openxlsx

解决方案


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

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) 

在此处输入图像描述


推荐阅读