加快ggplot绘图与ggarrange排版速度的方法咨询
加快ggplot绘图排版及PDF编译速度的方法
绘图排版优化
- 你测试的
ggarrange确实比grid.arrange更高效,可继续使用这类优化后的排版工具。另外推荐patchwork包,它底层实现更轻量,语法也更简洁,示例:
library(patchwork) # 横向排版两个图 myplot | myplot # 纵向排版两个图 myplot / myplot
- 提前预渲染所有绘图对象,像你把
myplot存为变量的做法,能避免在排版函数内重复执行ggplot代码,减少重复计算开销。 - 简化绘图复杂度:移除不必要的图层、用
theme_bw()/theme_minimal()替代复杂自定义主题、对大数据集做降采样,降低渲染计算量。
PDF编译优化
- 在R Markdown的YAML头部指定更高效的PDF渲染设备:
output: pdf_document: dev: cairo_pdf
- 给重复执行的代码块添加缓存,在代码块属性中加入
cache=TRUE,避免每次编译都重新生成相同图形。 - 合理设置绘图DPI,在代码块中指定
dpi=300即可满足PDF印刷需求,过高的DPI会大幅增加渲染时间。
你的性能测试结果
data=1:5 df <- data.frame(data) myplot <- ggplot(df)+geom_line(aes(x=data, y = data)) microbenchmark(grid.arrange(myplot, myplot), ggarrange(myplot, myplot), times=3)
Unit: milliseconds expr min lq mean median uq max neval grid.arrange(myplot, myplot) 107.0948 117.6475 153.5636 128.2002 176.7980 225.3959 3 ggarrange(myplot, myplot) 49.5275 49.5631 120.6860 49.5987 156.2653 262.9318
内容的提问来源于stack exchange,提问作者gaut
相关产品推荐
相关产品推荐

