ggplot2 width of boxplot

bsmith picture bsmith · Oct 24, 2017 · Viewed 33.8k times · Source

I was trying to make 2 separate plots which I want to present side by side in my poster (I need to make them separate and cannot make use of facet_wrap). One of the plots has several boxplots, while the second plot only has one. How can I manipulate the width of the boxplots such that the second boxplot is the same dimension as the width of any one of the individual boxplots in plot 1, when I put the two plots side by side? A reproducible example:

tvalues <- sample(1:10000,1200)
sex <- c(rep('M',600),rep('F',600))
region <- c('R1','R2','R3','R4','R5')
df1 <- data.frame(tvalues,sex,region)

tvalues2 <- sample(1:10000,200)
sex2 <- sample(c('M','F'),200,replace=T)
region2 <- 'R6'
df2 <- data.frame(tvalues2,sex2,region2)

p1 <- ggplot(data=df1,aes(x=region,y=tvalues,color=sex)) + 
geom_boxplot(width=0.5)
p2 <- ggplot(data=df2,aes(x=region2,y=tvalues2,color=sex2)) + 
geom_boxplot(width=0.5)

Plot 1 plot 1:

Plot2 plot 2:

Answer

Marco Sandri picture Marco Sandri · Oct 24, 2017

I suggest to divide the width of boxes in the second plot by the number of categories of region in the first plot.

p2 <- ggplot(data=df2,aes(x=region2,y=tvalues2,color=sex2)) + 
geom_boxplot(width=0.5/length(unique(df1$region)))

enter image description here