旋转辅助轴标签的文本

标签 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))

Example dual Axis plot with both axes labels rotated 我读过的任何文档(例如 scale_continuousthemes )都没有提到如何实现仅一个轴的旋转。

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

最佳答案

只要您有相对最新版本的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))

enter image description here

关于旋转辅助轴标签的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41118517/

相关文章:

R - 添加在组内按顺序计数但重复的列

r - 如何提取等高线图的特定边界?

r - 将强化的 data.frame 转换回 sf 对象

R ggplot2 - geom_point 自定义颜色范围和颜色

glmnet : NA/NaN/Inf in foreign function call 中的 R 错误

R:将一个矩阵中的元素替换为另一个矩阵中 NA 对应位置的元素

r - ggvis 将 ":= "与 data.table 结合使用

r - ggplot2等价于matplot():按列绘制矩阵/数组?

r - 双向密度图与 r 中选定区域的单向密度图相结合

删除字符串中第一次出现的下划线