旋转辅助轴标签的文本

sla*_*ine 6 r ggplot2

我正在利用ggplot2中最近添加的辅助轴标签功能.我想旋转辅助轴,但无法找到文档或计算出如何执行此操作.

它足够简单,可以使用...旋转所有文本

ggplot(mtcars, aes(x = wt, y = mpg, colour = mpg)) +
    geom_point() +
    scale_x_continuous(name = 'Bottom Axis',
                       sec.axis = sec_axis(trans = ~ .,
                                           name  = 'Top Axis',
                                           breaks = c(2:5),
                                           labels = c('Two Two', 'Three Three Three', 'Four Four Four Four', 'Five Five Five Five Five'))) +
## Rotate text of x-axis
    theme(axis.text.x = element_text(angle = 90))
Run Code Online (Sandbox Code Playgroud)

示例双轴图,两个轴标签都旋转 在我读过的任何文档中都没有提到它(例如scale_continuousthemes)如何实现只有一个轴的旋转.

我要求这样做的动机是,我希望应用于我的数据的一些标签是长的并且在水平放置时重叠,通过旋转它我可以避免这种情况,但我希望在底部轴上保持水平方向.

Axe*_*man 7

如果您运行的是最新开发版本ggplot2,你可以使用axis.text.x.top:

ggplot(mtcars, aes(x = wt, y = mpg, colour = mpg)) +
  geom_point() +
  scale_x_continuous(
    name = 'Bottom Axis',
    sec.axis = sec_axis(
      trans = ~ .,
      name  = 'Top Axis',
      breaks = 2:5,
      labels = c('Two Two', 'Three Three Three', 'Four Four Four Four', 'Five Five Five Five Five')
    )
  ) +
  ## Rotate text of x-axis
  theme(axis.text.x.top = element_text(angle = 45, hjust = 0))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 解决了,顺序很重要,我有一个后续的 `+ theme()` 应用于我的绘图,它正在擦除 `theme(axis.text.x.top = element_text(angle = 45, hjust = 0))` (刚刚添加如果其他人忘记顺序很重要,并且后续调用“theme()”可以擦除之前的调用)。 (2认同)