ggplot2 - Correctly arrange odd number of plots into one figure

后端 未结 4 1650
攒了一身酷
攒了一身酷 2020-12-19 11:42

I have an odd number of plots to arrange into one figure and I desire to show the last plot centered in the last row of the figure.

Here some sample data:

         


        
4条回答
  •  佛祖请我去吃肉
    2020-12-19 12:13

    You can use gridExtra::grid.arrange for this. All you need to do is specify the layout of the plots with a layout matrix.

    library(ggplot2)
    set.seed(99)
    
    x_1 = data.frame(z = rnorm(100))
    x_2 = data.frame(z = rnorm(100))
    x_3 = data.frame(z = rnorm(100))
    
    lst = list(x_1, x_2, x_3)
    
    lst_p = list()
    
    for (i in 1:length(lst)) {
    lst_p[[i]] = ggplot(data=lst[[i]], aes(lst[[i]]$z)) + 
    geom_histogram() +
    xlab("X LAB") +
    ylab("Y LAB") 
    }
    
    p_no_labels = lapply(lst_p, function(x) x + xlab("") + ylab(""))
    
    
    #layout of plots
    
    lay <- rbind(c(1,2),c(1,2),
                  c(3,3))
    
    
    
    #arrange the grid and specify the `layout_matrix`
    gridExtra::grid.arrange(grobs=p_no_labels, layout_matrix=lay)
    

提交回复
热议问题