【问题标题】:How to Arrange Stacked geom_bar by Ascending Proportion如何按比例升序排列堆叠的 geom_bar
【发布时间】:2020-12-28 16:41:22
【问题描述】:

我正在查看 R Tidy Tuesday 数据集(欧洲能源)。我已经将 Imports 和 Exports 作为比例进行了争论,并希望通过 Imports 值的上升来安排 ggplot。只是想让它看起来整洁,但似乎无法控制顺序,以查看具有下一个最大进口价值的每个后续国家。

我在代码中留下了几次尝试,但被注释掉了。提前谢谢。

library(tidyverse)

country_totals <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-08-04/country_totals.csv')


country_totals %>% 
  filter(!is.na(country_name)) %>% 
  filter(type %in% c("Imports","Exports")) %>% 
  group_by(country_name) %>% 
  mutate(country_type_ttl = sum(`2018`)) %>% 
  mutate(country_type_pct = `2018`/country_type_ttl) %>% 
  ungroup() %>% 
  mutate(type_hold = type) %>%
  pivot_wider(names_from = type_hold, values_from = `2018`) %>% 
  # ggplot(aes(country_name, country_type_pct, fill = type)) +
  # ggplot(aes(reorder(country_name, Imports), country_type_pct, fill = type)) +
  ggplot(aes(fct_reorder(country_name, Imports), country_type_pct, fill = type)) +
  geom_bar(stat = "identity") +
  coord_flip()

【问题讨论】:

    标签: r ggplot2 dplyr tidyverse geom-bar


    【解决方案1】:

    这可以通过添加一列来实现,其中包含您要重新排序的值,即 2018 年的进口份额百分比,例如imports_2018 = country_type_pct[type == "Imports"]。然后根据此列对计数器重新排序:

    `

    library(tidyverse)
    
    country_totals <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-08-04/country_totals.csv')
    
    country_totals %>% 
      filter(!is.na(country_name)) %>% 
      filter(type %in% c("Imports","Exports")) %>% 
      group_by(country_name) %>% 
      mutate(country_type_ttl = sum(`2018`)) %>% 
      mutate(country_type_pct = `2018`/country_type_ttl,
             imports_2018 = country_type_pct[type == "Imports"]) %>% 
      ungroup() %>% 
      mutate(type_hold = type) %>%
      ggplot(aes(fct_reorder(country_name, imports_2018), country_type_pct, fill = type)) +
      geom_bar(stat = "identity") +
      coord_flip()
    #> Warning: Removed 2 rows containing missing values (position_stack).
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-22
      • 1970-01-01
      • 1970-01-01
      • 2020-09-07
      • 1970-01-01
      • 1970-01-01
      • 2021-04-18
      相关资源
      最近更新 更多