I'm looking to assign a custom width to each row of a one column, facet-wrapped plot in R. (I know this is entirely non-standard.)
With grid.arrange
I can assign a unique height to each row of a facet-wrapped like plot with the following snippet:
group1 <- seq(1, 10, 2)
group2 <- seq(1, 20, 3)
x = c(group1, group2)
mydf <- data.frame (X =x , Y = rnorm (length (x),5,1),
groups = c(rep(1, length (group1)), rep(2, length(group2))))
plot1 <- ggplot(mydf, aes(X, Y)) + geom_point()
plot2 <- ggplot(mydf, aes(X, Y)) + geom_point()
grid.arrange(plot1, plot2, heights=c(1,2))
The code above gives each row of the plot a unique height:
I'm wondering if it's possible to assign a unique width to each row of the plot, rather than assign a unique height to each row. Is that even possible with any ggplot2 extension?
Yes this is possible if you use the plot.margin
functionality in the ggplot theme()
. You can set each plot width as a percent of the total length of the page by doing:
plot1 <- ggplot(mydf, aes(X, Y)) + geom_point()+theme( plot.margin = unit(c(0.01,0.5,0.01,0.01), "npc"))
plot2 <- ggplot(mydf, aes(X, Y)) + geom_point()+theme( plot.margin = unit(c(0.01,0.2,0.01,0.01), "npc"))
When we use npc
s as our unit of interest in the plot.margin
call, we are setting relative to the page width. The 0.5
and 0.2
correspond to the right margin. As npc
increases, the smaller your plot will get.
grid.arrange(plot1, plot2, heights=c(1,2))
As another option, you can use nullGrob
(a blank grob that just takes up space) to allocate horizontal space in a given row. For example:
library(gridExtra)
library(grid)
plot1 <- ggplot(mydf, aes(X, Y)) + geom_point()
plot2 <- ggplot(mydf, aes(X, Y)) + geom_point()
grid.arrange(arrangeGrob(plot1, nullGrob(), widths=c(1,1)),
plot2, heights=c(1,2))
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