使用Patchwork拼接ggplot2图表时消除间距问题排查与解决
用Patchwork拼接ggplot2图表时消除间距的问题解决
问题场景
尝试用Patchwork垂直拼接三个ggplot2图表,希望完全消除图表间的间距。已通过plot.margin设置边距为0,同时移除了轴刻度、文本和标签,但面板与绘图区域底部仍存在小间距,且单独绘制中间的p2图表时该间距也存在。
原可复现代码
x <- 1:100 p1 <- ggplot(data.frame(x,y=dnorm(x,50,10)),aes(x=x,y=y))+ geom_area(fill='green')+ theme(axis.text.x=element_blank(), axis.ticks.x=element_blank(), axis.title.x = element_blank(), plot.margin = margin(1,0,0,1,'line')) p2 <- ggplot(data.frame(x=sample(x,50)))+ geom_segment(aes(x=x,xend=x,y=0, yend=1))+ theme(axis.text=element_blank(), axis.ticks=element_blank(), axis.title.x = element_blank(), plot.margin = margin(0,0,0,1,'line')) p3 <- ggplot(data.frame(x,y=dnorm(x,20,5)),aes(x=x,y=y))+ geom_area(fill='blue')+ theme(plot.margin=margin(0,0,1,1,'line')) wrap_plots(p1,p2,p3,ncol=1,heights = c(4,1,4)) & theme(panel.background = element_rect(fill='gray90',color='black'), plot.background = element_rect(fill='lightyellow',color='blue'))
(注:原代码中p2行的+n为笔误,已修正)
问题根源
仅设置axis.ticks.x=element_blank()只是隐藏了刻度元素,但ggplot2仍然为轴刻度保留了默认的占位空间,这就是残留小间距的原因。
解决方法
在全局主题中添加axis.ticks.length.x=unit(0,'lines'),彻底取消轴刻度的占位空间,即可完全消除图表间的间距。
修改后的代码
wrap_plots(p1,p2,p3,ncol=1,heights = c(4,1,4)) & theme(panel.background = element_rect(fill='gray90',color='black'), plot.background = element_rect(fill='lightyellow',color='blue'), axis.ticks.length.x = unit(0,'lines'))
内容的提问来源于stack exchange,提问作者Osdorp
相关产品推荐
相关产品推荐

