Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering rotated labels when x-axis is at the top

Tags:

r

ggplot2

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.

x axis on the bottom

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")

x axis on the 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.

like image 381
Artem Sokolov Avatar asked Sep 14 '25 18:09

Artem Sokolov


1 Answers

Use axis.text.x.top instead:

gg + theme( axis.text.x.top =element_text(angle=90, vjust=.5)  ) +
  scale_x_continuous(position="top")

enter image description here

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

like image 65
astrofunkswag Avatar answered Sep 17 '25 08:09

astrofunkswag