R:将ggplot2图保存在不同的Excel工作表中

标签 r ggplot2 openxlsx

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

最佳答案

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) 

enter image description here

关于R:将ggplot2图保存在不同的Excel工作表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63121820/

相关文章:

将多个包含多个工作表的 xlsx 文件读取到一个 R 数据框中

r - "Error in addWorksheet(wb, "sheet1 ") : First argument must be a Workbook"

R - 自动调整 Excel 列宽

r - 将矩阵的元素与向量值相乘

r - 数值数据框列作为字符串的顺序不正确

在 lapply(.SD,...) 中为 data.table R 保留列名

r - 在 ggplot (R) 中手动设置 x 轴值

r - 将ggplot对象转换为在 Shiny 的应用程序中进行绘图

r - 基于置换法的方差分析中 F 统计量的 Monte Carlo 估计

r - directlabels geom_dl() 中的标签大小