Search code examples
rggplot2plotvisualizationr-grid

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?


Solution

  • 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