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.


