Set margins between plots using multiplot

后端 未结 3 610
粉色の甜心
粉色の甜心 2021-01-23 04:50

To display multiple plots I use multiplot (http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_(ggplot2)/), now I have two plots who share the same x-axis range and are

3条回答
  •  执念已碎
    2021-01-23 05:38

    It is easier than you might think to re-arrange the data so that you can take advantage of the nice alignment features that already exist in ggplot2. See below for an example replicating eipi10's answer, but without having to use ggplotGrob.

    What you have to do is just select the columns you want to plot, along with the ID columns (in this case, the car model and the x-axis value column). Then melt, and it's ready to plot using the standard facet procedure.

    Note that the "switch" option in the facet_grid call is a new feature that you can access by updating to the most recent CRAN version. I used that to replace the regular y-axis title, which was omitted using theme.

    The nice part about this approach is that the plots will always be perfectly aligned.

    library("ggplot2")
    library("dplyr")
    library("reshape2")
    
    df <- mtcars %>% 
      add_rownames(var = "Model") %>%
      select(Model, wt, mpg, carb) %>%
      melt(id.vars = c("Model","wt"))
    
    ggplot(df)+
      aes(x=wt, y=value)+
      geom_point()+
      theme(strip.background=element_blank())+
      facet_grid(variable ~ ., scales="free_y", switch="y")
    

提交回复
热议问题