Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 - Correctly arrange odd number of plots into one figure

Tags:

r

ggplot2

cowplot

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:

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(""))

title = cowplot::ggdraw() + cowplot::draw_label("test", size = 20)

p_grid = cowplot::plot_grid(plotlist = p_no_labels, ncol = 2)

print(cowplot::plot_grid(title, p_grid, 
                         ncol = 1, rel_heights = c(0.05, 1, 0.05)))

I want the 3rd plot at the centre of the figure. I am using cowplot.

Any suggestion? thanks

enter image description here

like image 887
aaaaa Avatar asked Oct 23 '18 16:10

aaaaa


People also ask

How to put multiple plots in one figure in ggplot?

To arrange multiple ggplot2 graphs on the same page, the standard R functions - par() and layout() - cannot be used. The basic solution is to use the gridExtra R package, which comes with the following functions: grid. arrange() and arrangeGrob() to arrange multiple ggplots on one page.

Does par() work with ggplot?

One disadvantage for par() is that it cannot work for ggplot, we can see below that the plot should appear on the upper left of the page, but it just happen as if par() isn't written here.


1 Answers

Using nested cowplot::plot_grids:

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(""))

title = cowplot::ggdraw() + cowplot::draw_label("test", size = 20)
top_row = cowplot::plot_grid(p_no_labels[[1]], p_no_labels[[2]], ncol=2)
bottom_row = cowplot::plot_grid(NULL, p_no_labels[[2]], NULL, ncol=3, rel_widths=c(0.25,0.5,0.25))

cowplot::plot_grid(title, top_row, bottom_row, ncol=1, rel_heights=c(0.1,1,1))

like image 196
wjchulme Avatar answered Oct 12 '22 14:10

wjchulme