Search code examples
rplotggplot2facet

Different size facets at x-axis


Length of x-axis is important for my plot because it allows one to compare between facets, therefore I want facets to have different x-axis sizes. Here is my example data:

group1 <- seq(1, 10, 2)
group2 <-  seq(1, 20, 3)
x = c(group1, group2)
mydf <- data.frame (X =x , Y = rnorm (length (x),5,1), 
                    groups = c(rep(1, length (group1)), rep(2, length(group2))))

And my code:

p1 = ggplot(data=mydf,aes(x=X,y=Y,color=factor(groups)) )+
  geom_point(size=2)+
  scale_x_continuous(labels=comma)+
  theme_bw()
p1+facet_grid(groups ~ .,scales = "fixed",space="free_x")

And the resulting figure:

enter image description here

Panel-1 has x-axis values less then 10 whereas panel-2 has x-axis value extending to 20. Still both panels and have same size on x-axis. Is there any way to make x-axis panel size different for different panels, so that they correspond to their (x-axis) values?

I found an example from some different package that shows what I am trying to do, here is the figure: enter image description here


Solution

  • Maybe something like this can get you started. There's still some formatting to do, though.

    library(grid)
    library(gridExtra)
    library(dplyr)
    library(ggplot2)
    
    p1 <- ggplot(data=mydf[mydf$groups==1,],aes(x=X,y=Y))+
      geom_point(size=2)+
      theme_bw()
    p2 <- ggplot(data=mydf[mydf$groups==2,],aes(x=X,y=Y))+
      geom_point(size=2)+
      theme_bw()
    
    summ <- mydf %>% group_by(groups) %>% summarize(len=diff(range(X)))
    summ$p <- summ$len/max(summ$len)
    summ$q <- 1-summ$p
    
    ng <- nullGrob()
    grid.arrange(arrangeGrob(p1,ng,widths=summ[1,3:4]),
                 arrangeGrob(p2,ng,widths=summ[2,3:4]))
    

    enter image description here

    I'm sure there's a way to make this more general, and the axes don't line up perfectly yet, but it's a beginning.