Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign unique width to each row of a facet_grid / facet_wrap plot

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:

enter image description here

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?

like image 476
duhaime Avatar asked Jun 15 '16 14:06

duhaime


2 Answers

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 npcs 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))

enter image description here

like image 114
Mike H. Avatar answered Nov 19 '22 21:11

Mike H.


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

enter image description here

like image 32
eipi10 Avatar answered Nov 19 '22 21:11

eipi10