在R/ggplot2中如何将表格与可视化绘图合并到同一张图片中
解决方案
方案1:使用patchwork+ggpubr直接拼接(推荐,无需额外转格式)
该方案直接使用ggplot生态内的表格组件生成静态表格,和你现有绘图代码的输出无缝拼接,可直接达到参考图效果:
首先安装依赖包:
install.packages(c("patchwork", "ggpubr"))
完整可运行代码:
library(ggplot2) library(gcookbook) library(plyr) library(patchwork) library(ggpubr) ce <- arrange(cabbage_exp, Date, Cultivar) # 原有绘图代码无需修改 data_plot <- ggplot(ce, aes(x = Date , y = Weight, fill = Cultivar)) + geom_bar(stat = 'identity') + geom_text(vjust = 1, aes(label = Weight), position = 'stack') # 生成对应表格对象,样式可通过ttheme自定义 data_table <- ggtexttable(ce, rows = NULL, theme = ttheme("light", base_size = 10)) # 上下拼接图形与表格,设置高度比为3:1,可按需调整 data_plot / data_table + plot_layout(heights = c(3, 1))
如果需要调整表格样式,修改ttheme的参数即可,支持自定义表头背景、单元格边框、字体颜色等效果。
方案2:保留formattable样式的拼接方法
如果你需要保留formattable生成的表格样式,可以先将formattable导出为静态图片,再和ggplot输出的图形拼接:
首先安装依赖包:
install.packages(c("webshot2", "magick")) # 第一次使用webshot2需要安装Chromium内核,运行下方代码即可自动安装 webshot2::install_chromium()
完整可运行代码:
library(ggplot2) library(gcookbook) library(plyr) library(formattable) library(webshot2) library(magick) ce <- arrange(cabbage_exp, Date, Cultivar) # 生成formattable表格并导出为临时图片 data_table <- formattable(ce) formattable::as.htmlwidget(data_table) |> htmltools::save_html(tempfile(fileext = ".html")) |> webshot(file = "temp_table.png", selector = ".formattable", zoom = 2) # 原有绘图代码无需修改,导出为临时图片 data_plot <- ggplot(ce, aes(x = Date , y = Weight, fill = Cultivar)) + geom_bar(stat = 'identity') + geom_text(vjust = 1, aes(label = Weight), position = 'stack') ggsave("temp_plot.png", data_plot, width = 8, height = 6, dpi = 300) # 读取两张图片拼接 plot_img <- image_read("temp_plot.png") table_img <- image_read("temp_table.png") # 调整表格宽度和上方图形宽度一致 table_img <- image_resize(table_img, paste0(image_info(plot_img)$width, "x")) # 上下拼接输出最终结果 final_img <- image_append(c(plot_img, table_img), stack = TRUE) image_write(final_img, "final_result.png") # 可选:删除过程临时文件 file.remove(c("temp_plot.png", "temp_table.png"))
内容的提问来源于stack exchange,提问作者anderwyang
相关产品推荐
相关产品推荐

