Ordering Bar Charts

Hi,

I am trying to order a stacked bar chart as shown in the example: Creating a barplot with ordered bars

I cant for the life of me get it to work. Could someone point out where I'm going wrong?

library(tidyverse)
region = sample(c('EU', 'AP', 'GU', 'PS', 'EL'), 20, replace = TRUE)
ctry = sample(c("wp", "vw", "ct", "vj", "yk", "uu", "xo", "av", "za", "zj", "lz", "vs", "fq"), 20, replace = TRUE)
items = sample(1:20)

mydf <- data.frame(region, ctry, items) %>% 
  mutate(ctry = factor(ctry, levels = unique(ctry)))

sorted_df_hard <- mydf %>%
  count(ctry, region) %>%
  arrange(ctry, -n)  %>% 
  mutate(ctry = factor(ctry, levels = unique(ctry)))

# of course, this is even worse
ggplot(sorted_df_hard, aes(x = ctry, y = n, fill = region)) +
  geom_bar(stat="identity") + 
  coord_flip()

The end result should have the ctry on the x-axis and the y axis should be counts with the region being the colour. It should sort it highest to lowest number of items

How about this:

library(tidyverse)
region = sample(c('EU', 'AP', 'GU', 'PS', 'EL'), 20, replace = TRUE)
ctry = sample(c("wp", "vw", "ct", "vj", "yk", "uu", "xo", "av", "za", "zj", "lz", "vs", "fq"), 20, replace = TRUE)
items = sample(1:20)

mydf <- data.frame(region, ctry, items) %>% 
  mutate(ctry = factor(ctry, levels = unique(ctry)))

sorted_df_hard <- mydf %>%
  count(ctry, region) %>%
  arrange(ctry, -n)  %>% 
  mutate(ctry = factor(ctry, levels = unique(ctry)), 
         ctry = forcats::fct_reorder(ctry, n, .fun = sum))

ggplot(sorted_df_hard, aes(x = ctry, y = n, fill = region)) +
  geom_bar(stat="identity") + 
  coord_flip()

Created on 2020-02-05 by the reprex package (v0.3.0)

You can achieve what (I think) you are trying to do by adding using forcats::fct_reorder on your ctry variable ordering by the sum of each factors n variable

1 Like

That is absolutely marvelous....Thank you ever so much

1 Like

No problem! If you wanted the bars in the reverse order (i.e. with the highest count on the bottom) than you could just add a forcats::fct_rev call after the fct_reorder function

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.