首页 > 解决方案 > 包含分类数据和大量注释的反向 x 轴

问题描述

我正在研究一个创建复杂ggplot图形的函数。除了条形图中的一些分类数据外,该图还有数十个文本和矩形注释。我想创建一个在某些情况下反转 x 轴的选项。因此,如果打开该选项,我需要添加一些逻辑来翻转轴。但是我遇到了障碍,因为反转数据的分组不会翻转注释(当然)。但我想翻转一切。

关于如何在不使海洋沸腾的情况下做到这一点的任何想法?

library(tidyverse)

mtcars %>%
  mutate( make =  word(rownames(mtcars))) %>%
  group_by(make) %>%
  summarize(wt = sum(wt)) %>%
  head ->
  mt

p <- ggplot(mt, aes(x = make, y = wt)) +
  geom_bar(stat = "identity") +
  annotate(
    "rect",
    xmin = 1.5,
    xmax = 4.5,
    ymin = 4,
    ymax = 7,
    alpha = .5
  )  + 
  annotate("label", x = 3, y = 6, label = "WTF, y'all?") 
p

scale_x_reverse我发现由于某种原因我什至无法使用:

p + scale_x_reverse() 
#> Error in -x: invalid argument to unary operator

请注意,我在此处的可重现示例已大大简化。在实践中,我的图表上有许多不同类型的元素。

标签: rggplot2

解决方案


scale_x_reverse用于连续缩放。在这里,您将需要使用因子和scale_x_discrete

library(tidyverse)

mtcars %>%
  mutate( make =  word(rownames(mtcars))) %>%
  group_by(make) %>%
  summarize(wt = sum(wt)) %>%
  head %>% 
  mutate( make = as.factor(make) ) -> # make `make` as a factor
  mt

p <- ggplot(mt, aes(x = make, y = wt)) +
  geom_bar(stat = "identity") +
  annotate(
    "rect",
    xmin = 1.5,
    xmax = 4.5,
    ymin = 4,
    ymax = 7,
    alpha = .5
  )  + 
  annotate("label", x = 3, y = 6, label = "WTF, y'all?") 
p

# reverse used order of factor levels
p + scale_x_discrete(limits = rev(levels(mt$make)))

在此处输入图像描述


推荐阅读