首页 > 解决方案 > 当 x 轴位于顶部时将旋转标签居中

问题描述

使旋转标签居中的标准技巧是使用vjust. 当轴位于底部时,它按预期工作:

library( ggplot2 )
gg <- ggplot( mtcars, aes(hp, mpg) ) + geom_point() + theme_bw()
gg + theme( axis.text.x=element_text(angle=90, vjust=0.5) )

蓝色轮廓显示标签相对于轴刻度正确居中。

x 轴在底部

但是,当 x 轴位于顶部时,我似乎无法达到相同的效果:

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

x 轴在顶部

vjust此外,当 x 轴位于顶部时,似乎没有效果。当我更改vjust为 0 或 1 时,我发现没有视觉差异。四处搜索相关帖子,我发现了一个 GitHub 问题,建议使用它来margin()代替hjust/ vjust。但是,无论 x 轴是位于顶部还是底部,我都无法让它使我的标签居中:

# 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

当 x 轴位于顶部时,是否有使标签居中的技巧?我想我总是可以深入挖掘 grobs 的层次结构,但我希望有一个更优雅的解决方案。

标签: rggplot2

解决方案


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


推荐阅读