反向x轴,其中包含分类数据和大量注释

时间:2018-12-11 12:46:08

标签: r ggplot2

我正在使用一个函数来创建复杂的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

请注意,这里的可复制示例已大大简化。实际上,我的图上有许多不同类型的元素。

2 个答案:

答案 0 :(得分:2)

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

enter image description here

答案 1 :(得分:1)

我们可以使注释标签和阴影成为输入数据的一部分。然后,注释将与x轴顺序一起反转。像这样:

library(tidyverse)

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

# Option to reverse, choose one
# if it is a function, pass an argument
# foo <- function(data, myReverseOption = FALSE, ...
myReverseOption = TRUE
myReverseOption = FALSE

mt$make <- as.factor(mt$make)

if(myReverseOption){
  mt$make <- factor(mt$make, levels = rev(levels(mt$make))) }

# add annotaions
mt <- mt %>% 
  mutate(
    myLabel = if_else(make == "Camaro", "OK, y'all?", NA_character_),
    myShade = grepl("^C", make))

# plot
ggplot(mt, aes(x = make, y = wt)) +
  geom_bar(stat = "identity") +
  geom_text(aes(label = myLabel), nudge_y = 1) +
  geom_rect(aes(xmin = (as.numeric(make) - 0.5) * myShade,
                xmax = (as.numeric(make) + 0.5) * myShade,
                ymin = 4, ymax = 6),
            alpha = 0.5) +
  ggtitle(ifelse(myReverseOption, "reversed", "original"))

enter image description here

enter image description here