25

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:

2 Answers 2

27

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

Sign up to request clarification or add additional context in comments.

Comments

7

In case of a single boxplot like in the following example:

a<- data.frame(obs=rep("A", 50),
       value=rnorm(50, 100, 50))

ggplot(a, aes(y=value))+
geom_boxplot()

Wide boxplot

We can establish a false x/y axis and establish an axis limit so the width option of geom_boxplot() determines the width of the box

ggplot(a, aes(y=value, x=0))+
geom_boxplot(width=0.7) + 
xlim(-1,1)

Thin boxplot

You can add the following to remove all x.axis text and ticks

theme(theme(axis.title.x = element_blank(), axis.text.x = element_blank(), axis.ticks.x = element_blank())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.