使用ggsave导出ggarrange绘图尺寸不符,如何正确设置参数?
解决ggarrange组合图用ggsave导出mm单位尺寸偏差问题
问题原因
ggarrange生成的是ggpubr自定义图形对象,ggsave对这类对象的毫米单位转换存在精度误差;同时默认主题的文本尺寸基于英寸设备设定,直接用mm导出时会导致文本相对画面比例失调。
解决方案
- 手动转换单位为英寸:按
1英寸=25.4mm将目标mm尺寸换算为英寸,规避ggsave的单位转换bug。 - 明确设置文本元素尺寸:在主题中指定文本的绝对大小,确保输出时比例协调。
- 精准指定绘图设备:导出特定格式时直接调用底层绘图函数,控制输出细节。
修改后的可运行代码
library(ggplot2) library(ggpubr) # 初始化数据 tmpDf <- data.frame(values1=1:12, values2=rev(101:112), group=rep(c("I", "II", "III"), 4)) # 初始化绘图,调整文本尺寸适配目标输出 tmpPlot <- ggplot(data=tmpDf, aes(x=values1, y=values2, color=group)) + geom_point() + ggtitle("Title") + theme_minimal() + theme( legend.position="bottom", axis.title.y=element_text(angle=0, vjust=0.5, size=8), axis.title.x=element_text(size=8), axis.text=element_text(size=6), plot.title=element_text(size=10), plot.caption=element_text(hjust=0, size=6), plot.title.position="plot", plot.caption.position="plot" ) # 组合图形 tmpPlotsGrouped <- ggarrange( tmpPlot, tmpPlot, tmpPlot, nrow=1, ncol=3, widths=c(1, 1, 1)) # 手动转换单位:mm转英寸 width_in <- 107 / 25.4 height_in <- 50 / 25.4 # 导出为jpg,用英寸单位确保尺寸准确 ggsave(file="myPath/plotName.jpg", plot=tmpPlotsGrouped, units="in", width=width_in, height=height_in, dpi=300) # 导出tiff格式(带无损压缩) ggsave(file="myPath/plotName.tiff", plot=tmpPlotsGrouped, units="in", width=width_in, height=height_in, dpi=300, device=tiff, compression="lzw")
额外说明
- 手动单位转换能保证输出尺寸严格匹配107mm×50mm的要求,避免ggsave内部换算的偏差。
- 固定文本尺寸后,文本与画面的比例在导出时会保持一致,不会出现过大或过小的问题。
- Tiff格式添加
compression="lzw"参数可生成无损压缩文件,适合学术出版等高精度需求场景。
内容的提问来源于stack exchange,提问作者Yacine Hajji
相关产品推荐
相关产品推荐

