0

我在问我是否可以从 R、一张表中的 huxtable 数据集和另一张表中的 ggplot2 绘图以及同一个 excel 文件中导出?

wb <- createWorkbook()
addWorksheet(wb, sheetName = "Frequencies")
addWorksheet(wb, sheetName = "Plot")

writeDataTable(wb, sheet = "Frequencies", x = huxtable, row.names=F)
plot(p)
insertPlot(wb,"Plot")

saveWorkbook(wb=wb, file="path_file/name_file.xlsx", overwrite=TRUE) 

我尝试使用上面的代码,这huxtable是格式化的数据集(数据集的行是彩色的),并且p是我使用函数生成的图ggplot(),但我没有得到所需的输出,因为我丢失了huxtable.

我尝试使用此代码,但它只导出带有格式的 huxtable 而不是绘图:

file<- as_Workbook(huxtable,sheet="Frequencies")

showGridLines(file, sheet="Frequencies", showGridLines = FALSE)

openxlsx::saveWorkbook(file,"file_path/file_name.xlsx", overwrite = TRUE)

这是情节和 huxtable 的示例:


p <- 
  ggplot(mtcars)+
  geom_histogram(aes(x = mpg))

p


huxtable<-as_hxtable(mtcars[1:10,])
for (i in 1:length(huxtable) ) {
  
  if  (i  == 1){
    huxtable<-set_background_color(huxtable,row=i  , everywhere, "yellow")  
  }
  
  
  else{
    huxtable<-set_background_color(huxtable,row=i  , everywhere, "red")
  }
  
}

huxtable

在此处输入图像描述

我想将彩色数据集 + 绘图导出到同一个 excel 文件中,而不会丢失数据集的格式

4

1 回答 1

2

这是一个可以调整的潜在工作流程。查看选项的包文档,因为下面的答案只使用最少的参数,并且所有使用的包都提供了很多选项。

在 OP 包含格式化的 huxtable 后更新。

library(openxlsx)
library(huxtable)
library(ggplot2)

# create workbook
wb <- createWorkbook()

#create sheet for plot
addWorksheet(wb, sheetName = "plot")


# create plot
p <- 
  ggplot(mtcars)+
  geom_histogram(aes(x = mpg))

p  

# insert plot inserts the current plot into the worksheet
insertPlot(wb, sheet = "plot")

# create huxtable with formatting
hx <- as_huxtable(mtcars[1:10,])

for (i in 1:length(hx) ) {
  
  if  (i  == 1){
    hx<-set_background_color(hx, row = i, everywhere, "yellow")  
  }
  
  
  else{
    hx<-set_background_color(hx, row = i, everywhere, "red")
  }
  
}

hx

在此处输入图像描述

# use huxtable::as_Workbook function to convert table for export into excel workbook
as_Workbook(hx, Workbook = wb, sheet = "table")


## Save workbook
saveWorkbook(wb, "eg_table_plot.xlsx", overwrite = TRUE)

reprex 包于 2021-12-02 创建(v2.0.1)

于 2021-12-02T20:43:51.947 回答