Side-by-side plots with ggplot2

后端 未结 13 2623
轮回少年
轮回少年 2020-11-22 02:06

I would like to place two plots side by side using the ggplot2 package, i.e. do the equivalent of par(mfrow=c(1,2)).

For example, I would like to have t

13条回答
  •  醉梦人生
    2020-11-22 02:35

    There is also multipanelfigure package that is worth to mention. See also this answer.

    library(ggplot2)
    theme_set(theme_bw())
    
    q1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
    q2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))
    q3 <- ggplot(mtcars) + geom_smooth(aes(disp, qsec))
    q4 <- ggplot(mtcars) + geom_bar(aes(carb))
    
    library(magrittr)
    library(multipanelfigure)
    figure1 <- multi_panel_figure(columns = 2, rows = 2, panel_label_type = "none")
    # show the layout
    figure1
    

    figure1 %<>%
      fill_panel(q1, column = 1, row = 1) %<>%
      fill_panel(q2, column = 2, row = 1) %<>%
      fill_panel(q3, column = 1, row = 2) %<>%
      fill_panel(q4, column = 2, row = 2)
    figure1
    

    # complex layout
    figure2 <- multi_panel_figure(columns = 3, rows = 3, panel_label_type = "upper-roman")
    figure2
    

    figure2 %<>%
      fill_panel(q1, column = 1:2, row = 1) %<>%
      fill_panel(q2, column = 3, row = 1) %<>%
      fill_panel(q3, column = 1, row = 2) %<>%
      fill_panel(q4, column = 2:3, row = 2:3)
    figure2
    

    Created on 2018-07-06 by the reprex package (v0.2.0.9000).

提交回复
热议问题