A standard trick for centering rotated labels is to use vjust
. It works as expected when the axis is at the bottom:
library( ggplot2 )
gg <- ggplot( mtcars, aes(hp, mpg) ) + geom_point() + theme_bw()
gg + theme( axis.text.x=element_text(angle=90, vjust=0.5) )
The blue outline shows that the labels are properly centered relative to the axis ticks.
However, I seem unable to achieve the same effect when the x axis is positioned at the top:
gg + theme( axis.text.x=element_text(angle=90, vjust=0.5) ) +
scale_x_continuous(position="top")
Furthermore, it appears that vjust
has no effect when the x axis is at the top. I found no visual difference when I changed vjust
to 0 or to 1. Searching around for related posts, I found a GitHub issue where it is suggested to use margin()
instead of hjust
/vjust
. However, I was not able to get it to center my labels regardless of whether the x axis was positioned at the top or the bottom:
# Top and bottom margins properly increase space between labels and axis ticks / title
gg + theme( axis.text.x=element_text(angle=90, margin=margin(t=10)) ) # Works
gg + theme( axis.text.x=element_text(angle=90, margin=margin(b=10)) ) # Works
# Left and right margins appear to have no effect
gg + theme( axis.text.x=element_text(angle=90, margin=margin(r=10)) ) # No effect
gg + theme( axis.text.x=element_text(angle=90, margin=margin(l=10)) ) # No effect
Is there a trick for getting labels centered when the x-axis is at the top? I suppose I can always go digging through the hierarchy of grobs, but I was hoping there is a more elegant solution.
Use axis.text.x.top
instead:
gg + theme( axis.text.x.top =element_text(angle=90, vjust=.5) ) +
scale_x_continuous(position="top")
Strange since the rotate still works. I'd like to see the package clarify this, but you can still get the behavior you're after
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With