Search code examples
rggplot2dplyrtidyversegeom-bar

How to Arrange Stacked geom_bar by Ascending Proportion


I'm am looking at an R Tidy Tuesday dataset (European Energy) . I have wrangled the Imports and Exports as proportions and am looking to arrange the ggplot with an ascend on the Imports values. Just looking to make it look tidy, but can't seem to control the order to see each subsequent country with the next biggest import value.

I have left a couple of attempts in the code but commented out. Thnx in advance.

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

Solution

  • This could be achieved by adding a column with the value by which you want to reorder, i.e. the percentage share of imports in 2018 using e.g. imports_2018 = country_type_pct[type == "Imports"]. Then reorder the counters according to this column:

    `

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