41

Consider the following

d = data.frame(y=rnorm(120), 
               x=rep(c("bar", "long category name", "foo"), each=40))

ggplot(d,aes(x=x,y=y)) + 
    geom_boxplot() + 
    theme(axis.text.x=element_text(size=15, angle=90))

plot with poorly aligned labels

The x-axis labels are aligned by the center of the label. Is it possible to automatically align on the right so that every label would end right below the graph?

2 Answers 2

68

This is precisely what the hjust and vjust parameters are for in ggplot. They control the horizontal and vertical justification respectively and range from 0 to 1. See this question for more details on justifications and their values (What do hjust and vjust do when making a plot using ggplot?).

To get the labels the way you want you can use:

  • hjust = 0.95 (to leave some space between the labels and the axis)
  • vjust = 0.2 (to center them in this case)

ggplot(d,aes(x=x,y=y)) + geom_boxplot() + 
       theme(axis.text.x=element_text(size=15, angle=90,hjust=0.95,vjust=0.2))

enter image description here

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

2 Comments

Why does the long name not align with the others? The final "e" in "long category name" is closer to the tick mark than "bar" or "foo".
That's not an ideal solution tho. The three labels don't perfectly align. 'bar' and 'foo' are further away from the axis that 'long categroy name'. Is there really no better solution to this?
19

Alternatively, flip the axis, your customers will thank you and have less neck pain (plus, I find most boxplots easier to interpret with this orientation):

ggplot(d, aes(x = x, y = y)) +
  geom_boxplot() + 
  coord_flip()

Plot

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.