r - 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
解决方案
在 的帮助下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)
推荐阅读
- java - 在 Java 中实现 LRU 缓存
- reactjs - 尝试从“react-native”导入 AppRegistry 后无法编译未找到的模块
- javascript - 无法安装组件:未定义模板或渲染函数。组件导入失败
- flutter - Flutter FutureBuilder widget not responding to Future resolution when chaining Futures with await
- google-cloud-build - Cloud Build 中的 imageurl 是什么?
- java - 如何从 Java 控制器访问变量?JavaFX,场景生成器
- chatbot - 在没有邀请的情况下作为 Slack 机器人写入直接消息
- reactjs - 在父组件中,有什么方法可以从子组件访问道具?
- node.js - 每个 API 请求都会创建 Express-session 新会话
- r - R - data.table 中两列的滚动总和