2

I created a horizontal boxplot in ggplot2 (de-identified image below). What I'm trying to figure out is a way to reduce the size of the space on the y-axis (which is really the discrete x-axis), i.e. the height of the space from the top to "label1" and the same space at the bottom. I haven't had any luck so far. It looks like the axis goes from about 0 to 3 or so, with the lower box from 0.5-1.5 and the upper box from 1.5-2.5. If that's the case, I'd like the axis to go from about 0.3-2.7.

ggplot(box,aes(X_NAME_,COL1))+geom_boxplot()+
labs(y=NULL,x=NULL)+
stat_summary(fun.y=mean,geom='point')+theme_classic()+
annotate('text',y=4,x=2.5,label='label1')+
annotate('text',y=-2.25,x=1.5,label='label2')+
scale_x_discrete(labels=NULL)+theme(axis.ticks.y=element_blank())+
theme(axis.line.y=element_blank())+
scale_y_continuous(limits=c(-40,40))+
annotate('rect',xmin=0,xmax=3,ymin=-40,ymax=0, alpha=0.1)+
annotate('rect',xmin=0,xmax=3,ymin=0,ymax=40, alpha=0.3)+
coord_flip()

boxplot

1 Answer 1

3

Have a look at the expand argument of scale_y/x_*:

?scale_x_discrete

expand A numeric vector of length two giving multiplicative and additive expansion constants. These constants ensure that the data is placed some distance away from the axes. The defaults are c(0.05, 0) for continuous variables, and c(0, 0.6) for discrete variables.

... +
scale_x_discrete(labels = NULL, expand = c(0, .2)) +
...

should do the trick in this case.

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

4 Comments

I'm a bit confused, you said scale_y but then wrote scale_x. Are you talking about using expand within my scale_x_discrete statement or scale_y_continuous?
Yea, sry, edited. The argument applies to both. In your case you should put it in scale_x_continuous
Why does it go under continuous instead of discrete? It is a discrete axis.
You are right. It works with any x/y scale thou, continuous or discrete.

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.