【问题标题】:Centering rotated labels when x-axis is at the top当 x 轴位于顶部时将旋转标签居中
【发布时间】:2020-05-06 16:05:05
【问题描述】:

使旋转标签居中的标准技巧是使用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 轴位于顶部时,我似乎无法达到相同的效果:

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

此外,当 x 轴位于顶部时,vjust 似乎无效。当我将vjust 更改为 0 或 1 时,我发现没有视觉差异。搜索相关帖子,我发现a GitHub issue 建议使用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 的层次结构,但我希望有一个更优雅的解决方案。

【问题讨论】:

  • 这绝对是一个错误。有用的说明:为element_text(...) 命令设置debug=TRUE。它将在文本元素周围绘制一个淡黄色框,然后在文本元素锚定的位置添加黄色点。当角度=0 时,将vjust=hjust= 设置为不同的值,您会看到锚点四处移动。当您使用顶部的文本执行此操作时,vjust= 不再执行任何操作

标签: r ggplot2


【解决方案1】:

改用axis.text.x.top

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

奇怪,因为旋转仍然有效。我希望看到包裹澄清这一点,但你仍然可以得到你所追求的行为

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2019-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多