Extend axis limits without plotting (in order to align two plots by x-unit)

前端 未结 2 589
滥情空心
滥情空心 2020-12-19 03:44

I am trying to combine two ggplot objects with patchwork - two plots with different subsets of data, but the same x variable (and therefore same unit). I would

2条回答
  •  半阙折子戏
    2020-12-19 04:21

    Here is an option with grid.arrange that does not use a blank plot, but requires a manual of adjustment of:

    • plot margin
    • x axis expansion
    • number of decimal places in y axis labels
    library(ggplot2)
    library(dplyr)
    library(gridExtra)
    
    p1 <- 
      ggplot(mtcars, aes(mpg)) + 
      geom_density(trim = TRUE) +
      scale_x_continuous(limits = c(10,35), breaks=seq(10,35,5), expand = expand_scale(add=c(0,0))) 
    
    p2 <- 
      ggplot(filter(mtcars, mpg < 20), aes(mpg)) + 
      geom_histogram(binwidth = 1, boundary = 1) +
      scale_x_continuous(limits = c(10,20), breaks=seq(10,20,5), expand = expand_scale(add=c(0,0))) +
      scale_y_continuous(labels = scales::number_format(accuracy = 0.01)) +
      theme(plot.margin = unit(c(0,1,0,0), "cm"))
    
    grid.arrange(p1, p2,
      layout_matrix = rbind(c(1, 1), c(2, NA))
    )
    

    Should make this plot:

提交回复
热议问题