mrz123456
mrz123456

Reputation: 41

How do I fix the size of multiple ggplot plots?

I noticed when combining multiple ggplots, where the values in one are much larger than the other, because the y axis ticks are larger in the former (due to being bigger numbers), it makes the plot itself smaller. To illustrate:

df <- data.frame('name'=1:30,'v1'=rpois(30, 1),'v2'=rpois(30, 100))
p1 <- ggplot(data=df,aes(x=name,y=v1)) + geom_bar(stat = 'identity')
p2 <- ggplot(data=df,aes(x=name,y=v2)) + geom_bar(stat = 'identity')
combined <- ggarrange(p1, p2, ncol=1, nrow=2)
print(combined)

two barcharts produced

Note that the bottom plot is slightly smaller than the top plot, because the the numbers in the y-ticks are larger. Is there anyway to make it so that the plots themselves are exactly the same size? (That doesn't involve manually changing the tick sizes until the plots look approximately the same). I tried using ggplotGrob(), which was suggested elsewhere, but it didn't seem to help. Thanks.

Upvotes: 3

Views: 326

Answers (2)

TarJae
TarJae

Reputation: 79246

Just add library(egg) It seems that you have loaded library(ggpubr) that also have a ggarrange function:

library(egg)

df <- data.frame('name'=1:30,'v1'=rpois(30, 1),'v2'=rpois(30, 100))
p1 <- ggplot(data=df,aes(x=name,y=v1)) + geom_bar(stat = 'identity')
p2 <- ggplot(data=df,aes(x=name,y=v2)) + geom_bar(stat = 'identity')
combined <- ggarrange(p1, p2, ncol=1, nrow=2)
print(combined)

enter image description here

Upvotes: 1

Dan Adams
Dan Adams

Reputation: 5254

The {patchwork} library does this nicely by default.

library(tidyverse)
library(patchwork)

df <- data.frame('name'=1:30,'v1'=rpois(30, 1),'v2'=rpois(30, 100))
p1 <- ggplot(data=df,aes(x=name,y=v1)) + geom_bar(stat = 'identity')
p2 <- ggplot(data=df,aes(x=name,y=v2)) + geom_bar(stat = 'identity')

p1/p2

Created on 2022-01-27 by the reprex package (v2.0.1)

Upvotes: 2

Related Questions