【问题标题】:Using `scale_y_discrete` to include variables in label names reorders labels without reordering the data使用 `scale_y_discrete` 在标签名称中包含变量重新排序标签而不重新排序数据
【发布时间】:2021-12-09 04:04:06
【问题描述】:

假设我有以下数据:

library(tidyverse)

set.seed(123)

col <- tibble(
  name = toupper(letters[1:20]),
  share = round(rnorm(20, 0.5, 0.1), 2),
  active_days = sample.int(50, 20)
)

使用scale_y_discrete(),按照上面的代码绘制,我们得到:

col %>%
  ggplot(aes(y = reorder(name, share), x = share)) +
  geom_col() +
  labs(x = "Share",
       y = "Merchant")

我想将active_days 的值添加到图中每个商家的标签中。这可以使用scale_y_discrete 来实现:

col %>%
  ggplot(aes(y = reorder(name, share), x = share)) +
  geom_col() +
  labs(x = "Share",
       y = "Merchant") +
  scale_y_discrete(labels = paste0(col$name, " (", col$active_days, ")"))

但是,添加 scale_y_discrete 会将标签的顺序更改为反转字母顺序,但值/条会按降序正确显示,在这种情况下,给人的印象是商家 T 拥有最高份额,而它其实是商家P!这显然是非常不受欢迎的。任何人都知道这里发生了什么,以及如何补救?

【问题讨论】:

    标签: r ggplot2 dplyr


    【解决方案1】:

    @teunbrand 的答案完全正确。

    如果您的情况允许,在绘图之前设置因子水平可能会更容易。

    library(tidyverse)
    
    set.seed(123)
    
    col <- tibble(
      name = toupper(letters[1:20]),
      share = round(rnorm(20, 0.5, 0.1), 2),
      active_days = sample.int(50, 20)
    )
    
    col %>%
      mutate(breaks = paste0(name, "(", active_days, ")" )) %>% 
      mutate(breaks = fct_reorder(breaks, share)) %>% 
      ggplot(aes(y = breaks, x = share)) +
      geom_col() +
      labs(x = "Share",
           y = "Merchant")
    

    reprex package 创建于 2021-10-22 (v2.0.1)

    【讨论】:

      【解决方案2】:

      由于重新排序,原始 data.frame 中的顺序与离散比例感知的顺序不同步。如果数据中没有重复的names,可以将轴标签的值与原始数据进行匹配,查找对应的值。

      library(tidyverse)
      #> Warning: package 'tibble' was built under R version 4.1.1
      #> Warning: package 'tidyr' was built under R version 4.1.1
      #> Warning: package 'readr' was built under R version 4.1.1
      
      set.seed(123)
      
      col <- tibble(
        name = toupper(letters[1:20]),
        share = round(rnorm(20, 0.5, 0.1), 2),
        active_days = sample.int(50, 20)
      )
      
      col %>%
        ggplot(aes(y = reorder(name, share), x = share)) +
        geom_col() +
        labs(x = "Share",
             y = "Merchant") +
        scale_y_discrete(
          labels = ~ paste0(
            .x, " (", col$active_days[match(.x, col$name)], ")"
          )
        )
      

      reprex package (v2.0.1) 于 2021 年 10 月 22 日创建

      【讨论】:

      • 它有效 - 谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-02
      • 2018-11-29
      • 1970-01-01
      • 1970-01-01
      • 2016-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多