I want to obtained an unbalanced grid of plots such as
require(ggplot2)
require(gridExtra)
df <- data.frame(value1 = rnorm(200),
value2 = rnorm(200),
value3 = rnorm(200),
value4 = rnorm(200))
p1 <- ggplot(df) + geom_density(aes(x=value1))
p2 <- ggplot(df) + geom_density(aes(x=value2))
p3 <- ggplot(df) + geom_density(aes(x=value3))
p4 <- ggplot(df) + geom_density(aes(x=value4))
grid.arrange(p1, arrangeGrob(p2,p3,p4, ncol=3), heights=c(2.5/4, 1.5/4), ncol=1)
but using a function
myplot <- function(i){
p <- ggplot(df) + geom_density(aes_string(x=i))
return(p)
}
and an lapply
call
p <- lapply(c("value1","value2","value3","value4"), myplot)
do.call(grid.arrange, c(p))
In this case grid.arrange
distribute the plots in a 2 by 2 matrix. But I want to obtain an unbalanced layout as with
grid.arrange(p1, arrangeGrob(p2,p3,p4, ncol=3), heights=c(2.5/4, 1.5/4), ncol=1)
If layout parameters are ommitted altogether, grid. arrange() will calculate a default number of rows and columns to organise the plots. More complex layouts can be achieved by passing specific dimensions (widths or heights), or a layout matrix defining the position of each plot in a rectangular grid.
Creating a Grid of Plots To do this, you use the parameter value mfrow=c(x,y) where x is the number of rows that you wish to have in your plot and y is the number of columns. When you plot, R will place each plot, in order by row within the grid that you define using mfrow .
The base R functions such as par() and layout() will not work with ggplot2 because it uses a different graphics system and this system does not recognize base R functionality for plotting. However, there are multiple ways you can combine plots from ggplot2 . One way is using the cowplot package.
First off a grob is just short for “grid graphical object” from the low-level graphics package grid; Think of it as a set of instructions for create a graphical object (i.e. a plot). The graphics library underneath all of ggplot2's graphical elements are really composed of grob's because ggplot2 uses grid underneath.
You can now do,
grid.arrange(p1,p2,p3,p4, layout_matrix = rbind(c(1,1,1),c(2,3,4)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With