Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aligning / setting width of margin/figure region in ggplot2

Tags:

r

ggplot2

I need to position several plots below each other and I want the widths of the margin and figure regions to be identical, so they align neatly. Note, that I need two single plots, not one joint plot. I want to save each one in a separate PNG file. I just want their structure (margin, figure region size) to be identical.

library(ggplot2)

d <- data.frame(label=c("some very longe label with lots of text", 
                        "another long label with lots of text", 
                        "short", 
                        "also short",
                        "                                     short", 
                        "                                also short"), 
                        x = 1:6)

ggplot(d[1:2, ], aes(label, x)) + geom_bar(stat = "identity")  + coord_flip()
ggplot(d[3:4, ], aes(label, x)) + geom_bar(stat = "identity")  + coord_flip()

enter image description here enter image description here

What I want is plot 2 to have the same left margin width as in plot 1, more or less like below, of course without adding extra blanks ;)

enter image description here

In base graphics I would just set par("mar") accordingly.

How can I achieve this in ggplot?

like image 448
Mark Heckmann Avatar asked Dec 19 '16 22:12

Mark Heckmann


1 Answers

Based on the answer from the last link from the comment above, you can equate the widths of the plots. The only difference from that answer is that they are not combined.

So for your plots

library(ggplot2)
p1 <- ggplot(d[1:2, ], aes(label, x)) + geom_bar(stat = "identity")  + coord_flip()
p2 <- ggplot(d[3:4, ], aes(label, x)) + geom_bar(stat = "identity")  + coord_flip()

Equate widths of plot

library(grid)
gl <- lapply(list(p1,p2), ggplotGrob)  
wd <- do.call(unit.pmax, lapply(gl, "[[", 'widths'))
gl <- lapply(gl, function(x) {
        x[['widths']] = wd
        x})

Plot

grid.newpage(); grid.draw(gl[[1]])
grid.newpage(); grid.draw(gl[[2]])

Which produces:

Plot 1

enter image description here

Plot 2

enter image description here

like image 163
user20650 Avatar answered Sep 20 '22 23:09

user20650