Patchwork + ggplot2 margins

211 views Asked by At

Sorry in advance if this topic has been addressed, but I could not find a solution.

I am trying to make a composition of three ggplots with patchwork and I would like to completely remove the space between them. I have read in multiple sites that the margin is controlled by plot.margin. I have removed the axis ticks, text and labels and set the margin to zero. However, I still have a small margin at the bottom between the panel and the plot area. What am I missing?

I don't think it is related to patchwork, since plotting p2 in the example bellow also leaves a small margin between the panel and the plot area.

Here is a reproducible example with nonsense data:

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'))

enter image description here

Thanks for your time

EDIT: OK, I found the issue playing around with all theme options. Apparently, axis.ticks.x=element_blank() still leaves the space for the ticks. Adding axis.ticks.length.x=unit(0,'lines') completely removes the margins.

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'))

Result using axis.ticks.length.x=unit(0,'lines'

0

There are 0 answers