【问题标题】:How to order facets based on facet_wrap from Y values?如何根据 Y 值中的 facet_wrap 对构面进行排序?
【发布时间】:2020-12-18 06:04:42
【问题描述】:

有没有办法根据它们的 Y 值(又名 count )以动态降序重新排序这些方面 - 无需对顺序进行硬编码(给定与 package 类似的列,具有数百个级别?

  library(cranlogs)
  library(tidyverse)   

  tidyverse_downloads <- cran_downloads(
      packages = pkgs,
      from     = "2017-01-01",
      to       = "2017-06-30") %>%
      tibble::as_tibble() %>%
      group_by(package)



  tidyverse_downloads %>%
     ggplot(aes(x = date, y = count)) +
     #geom_hline(yintercept = 0, color = "grey40") +
     geom_line() +
     #geom_smooth(method = "loess") +
     theme_minimal() +
     facet_wrap(~ package, scale = "free_y",ncol = 2) + theme(axis.text.x = element_text(angle = 90, hjust = 1))

我尝试的是使用包库(tidytext)和scale_y_reordered

   tidyverse_downloads %>%
     mutate(count = tidytext::reorder_within(count, date, package)) %>% 
     tidytext::scale_y_reordered() +
     ggplot(aes(x = date, y = count)) +
     geom_line() +
     theme_minimal() +
     facet_wrap(~ package, scale = "free_y",ncol = 2) + theme(axis.text.x = element_text(angle = 90, hjust = 1))

但是,这不会产生任何结果。我猜我做错了什么。感谢任何帮助

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您可以将每个包的总下载量相加,以按降序收集因子水平。

    library(cranlogs)
    library(tidyverse) 
    
    pkgs <- c('dplyr', 'broom', 'ggplot2', 'purrr')
      
    tidyverse_downloads <- cran_downloads(
      packages = pkgs,
      from     = "2017-01-01",
      to       = "2017-06-30") %>%
      tibble::as_tibble()
    
    
    tidyverse_downloads %>%
      group_by(package) %>%
      summarise(count = sum(count)) %>%
      arrange(desc(count)) %>%
      pull(package) -> levels
    
    levels
    #[1] "ggplot2" "dplyr"   "purrr"   "broom"  
    

    根据上面的levels 分配package 中的级别。

    tidyverse_downloads %>%
      mutate(package = factor(package, levels)) %>%
      ggplot(aes(x = date, y = count)) +
      geom_line() +
      theme_minimal() +
      facet_wrap(~ package, scale = "free_y",ncol = 2) + 
      theme(axis.text.x = element_text(angle = 90, hjust = 1))
    

    【讨论】:

      猜你喜欢
      • 2017-07-08
      • 1970-01-01
      • 1970-01-01
      • 2014-01-14
      • 1970-01-01
      • 2020-04-10
      • 1970-01-01
      • 1970-01-01
      • 2015-11-08
      相关资源
      最近更新 更多