如何使用writexl包在Excel中导出ggplot图表与R数据框?
解决方案:结合writexl与openxlsx实现数据+图表导出到Excel
writexl包仅支持导出数据到Excel,不具备插入图表/图片的功能。要实现同时导出数据和图表到同一Excel文件,需要结合openxlsx包(支持操作Excel并插入图片)来完成。
完整实现代码
首先加载所需包:
library(tidyverse) library(writexl) library(openxlsx)
1. 生成数据与图表
# 创建数据框 a = rnorm(10) b = runif(10) var = c(rep("chair",5),rep("table",5)) d = tibble(a,b,var) # 生成ggplot图表 p2 = ggplot(data = d, aes(x=var, y=a)) + geom_boxplot(aes(fill=a), outlier.shape=NA)+ facet_wrap(~var, scales="free")+ ggtitle("boxs")
2. 用writexl导出数据到Excel
excel_path = "path\\name_file.xlsx" # 替换为你的文件路径 writexl::write_xlsx(list(data=d), path = excel_path)
3. 保存图表为临时图片并插入Excel
情况1:图表单独存放在新工作表
# 保存图表为临时PNG文件(可调整宽高) temp_plot = tempfile(fileext = ".png") ggsave(temp_plot, plot = p2, width = 6, height = 4) # 打开已生成的Excel文件 wb = loadWorkbook(excel_path) # 添加新工作表用于存放图表 addWorksheet(wb, sheetName = "图表") # 将图片插入新工作表的指定位置 insertImage(wb, sheet = "图表", file = temp_plot, startRow = 1, startCol = 1, width = 6, height = 4) # 保存修改后的Excel文件 saveWorkbook(wb, excel_path, overwrite = TRUE)
情况2:图表插入到数据所在的同一工作表
# 保存图表为临时PNG文件 temp_plot = tempfile(fileext = ".png") ggsave(temp_plot, plot = p2, width = 6, height = 4) # 打开Excel文件 wb = loadWorkbook(excel_path) # 获取数据行数,将图表插在数据下方 data_row_count = nrow(d) # 插入图表到数据工作表的第data_row_count+2行 insertImage(wb, sheet = "data", file = temp_plot, startRow = data_row_count + 2, startCol = 1, width = 6, height = 4) # 保存文件 saveWorkbook(wb, excel_path, overwrite = TRUE)
简化方案:直接用openxlsx完成所有操作
如果不需要单独用writexl,也可以直接用openxlsx同时写入数据和插入图表,步骤更连贯:
wb = createWorkbook() # 添加数据工作表并写入数据 addWorksheet(wb, "data") writeData(wb, "data", d) # 保存图表并插入到新工作表 temp_plot = tempfile(fileext = ".png") ggsave(temp_plot, plot = p2, width = 6, height = 4) addWorksheet(wb, "图表") insertImage(wb, "图表", temp_plot, startRow = 1, startCol = 1) # 保存Excel文件 saveWorkbook(wb, excel_path, overwrite = TRUE)
内容的提问来源于stack exchange,提问作者Homer Jay Simpson
相关产品推荐
相关产品推荐

