使用plot_grid合并ggplot与flextable表格时分辨率损失如何解决
解决方案
核心思路是跳过栅格转换步骤,直接将flextable转为矢量格式的grid图形对象(grob),完全保留原始表格的线条精度和显示效果。
修改后的可运行代码
library(ggplot2) library(cowplot) library(flextable) library(grid) # 生成示例ggplot图表 Graph1 <- data.frame(x = 1:100, y = runif(100)) # 修正原代码的数据源错误 Graph <- ggplot(Graph1, aes(x = x)) + geom_line(aes(y = y)) + scale_x_continuous(expand = c(0,0)) # 原代码对连续x轴误用离散轴设置,已修正 # 生成flextable `Sample name` <- c("Media1", "Media2") `Valore medio Peel (N)` <- c(4.35, 4.31) `Valore massimo Peel (N)` <- c(5.5, 6.5) df <- data.frame(`Sample name`, `Valore medio Peel (N)`, `Valore massimo Peel (N)`, check.names = FALSE) ft <- flextable(df) ft <- set_header_labels(ft, Sample.name = "Sample name", `Valore.medio.Peel..N.` = "Valore medio peel (N)", `Valore.massimo.Peel..N.`= "Valore massimo Peel (N)") ft <- set_table_properties(ft, layout = "autofit", width = .6) ft <- bold(ft, bold = TRUE, part = "header") # 关键:将flextable转为矢量grob,不需要转栅格 ft_grob <- gen_grob(ft, fit = "auto") # 直接合并ggplot和表格grob plot_grid(Graph, ft_grob, labels = NULL, ncol = 1, nrow = 2, scale = c(1, .75))
补充说明
- 若需导出结果,优先保存为PDF、SVG等矢量格式,可完全保留无损耗的显示效果;若保存为PNG格式,设置
dpi = 300及以上即可获得远高于栅格转换方案的清晰度。 - 原代码中存在的两个小错误已同步修正:一是ggplot数据源误写为
Graph(应为Graph1),二是连续型x轴误用了scale_x_discrete,调整后代码可直接运行。
内容的提问来源于stack exchange,提问作者GiacomoDB
相关产品推荐
相关产品推荐

