Search code examples
rggplot2bar-charttidyversestacked-chart

How to order a dodged bar chart?


I am having issues ordering in a descending order a dodged bar chart. The dataset contains cities and prices for specific items in those cities for going out (e.g. taxi, drinks, dinner etc.) - dataset can be found here: https://data.world/makeovermonday/2018w48

Reprex:

City <- c("Mexico City", "Prague", "Moscow", "Mexico City","Prague", "Moscow")
Category <- c("Date Night", "Date Night","Date Night", "Party Night", "Party Night", "Party Night")
TotalCost <- c(84.82, 86.52, 20.35, 46.29, 19, 26.56)

CostNightPrepared <- data.frame(City,Category,TotalCost)

I modified the dataset to only show me City ,Category(type of a night out) and TotalCost which is the total sum price of each category per city:

CostNightPrepared <- CostNight  %>%
  group_by(City, Category) %>%
  summarize(TotalCost = sum(Cost, na.rm = TRUE))%>%
  arrange(Category, TotalCost)

To visualise the dataset:

ggplot(CostNightPrepared, aes(TotalCost, fct_rev(fct_reorder(City, TotalCost)), fill=Category)) + 
  geom_bar(stat="identity",position = position_dodge(width = 0.5))

As you can see, I played around withfct_rev and fct_reorder(), however the output is still this:

enter image description here

How do I order the dodged (overlapping) bar chart for the 'Party Night' category in a descending order?


Solution

  • Filter the data first for 'Party night', summarise the data and extract the city names in increasing order of Cost.

    CostNightPrepared %>%
      filter(Category == 'Party night') %>%
      group_by(City) %>%
      summarise(aveg = mean(Cost)) %>%
      arrange(aveg) %>%
      pull(City) -> lvls
    

    Rearrange the factor levels, summarise the data and plot.

    CostNightPrepared %>%
      mutate(City = factor(City, lvls)) %>%
      group_by(City, Category) %>%
      summarise(Cost = mean(Cost)) %>%
      ggplot(aes(Cost, City, fill=Category)) + 
      geom_bar(stat="identity",position = position_dodge(width = 0.5))
    

    enter image description here