簡體   English   中英

將一個 huxtable 數據和一個 ggplot 導出到一個 excel 文件中

[英]export a huxtable data and a ggplot into one excel file

I'm asking if I could export from R, a huxtable dataset in one sheet and a plot from ggplot2 in another sheet, and in the same excel file?

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) 

I tried with the above code, the huxtable is the formatted dataset (rows of the dataset are colored), and p is the plot that I generated using the function ggplot() , but I didn't get the required output because I lost the從huxtable格式化。

我嘗試使用此代碼,但它只導出帶有格式的 huxtable,而不是 plot:

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

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

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

這是 plot 和 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

在此處輸入圖像描述

我想在不丟失數據集格式的情況下將彩色數據集 + plot 導出到同一個 excel 文件中

這是一個可以調整的潛在工作流程。 查看 package 文檔以獲取選項,因為下面的答案僅使用最少的 arguments 並且所有使用的包都提供了很多選項。

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")
  }
  
}

head(hx)

               mpg   cyl   disp    hp   drat     wt   qsec  
              21       6    160   110   3.9    2.62   16.5  
              21       6    160   110   3.9    2.88   17    
              22.8     4    108    93   3.85   2.32   18.6  
              21.4     6    258   110   3.08   3.21   19.4  
              18.7     8    360   175   3.15   3.44   17    

列名:mpg、cyl、disp、hp、drat、wt、qsec、vs、am、gear、carb

顯示 7/11 列。

# 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)

代表 package (v2.0.1) 於 2021 年 12 月 2 日創建

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM