我在問我是否可以從 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 檔案中
uj5u.com熱心網友回復:
這是一個可以調整的潛在作業流程。查看選項的包檔案,因為下面的答案只使用最少的引數,并且所有使用的包都提供了很多選項。
在 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 包(v2.0.1)于 2021 年 12 月 2 日創建
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/376602.html
