Home > Software engineering >  R - Issues with group order/ ggplot dodge barchart
R - Issues with group order/ ggplot dodge barchart

Time:02-12

I looked through other questions but I didn't find this exact problem

company<-c("c1","c1","c2","c2","c2","c3","c3","c3","c4","c4", "c4")
subsegment<- c("Sub2","Sub3", "Sub1","Sub2", "Sub3", "Sub1","Sub2", "Sub3", "Sub1","Sub2", "Sub3")
values<-c(120,300,30,300,1800,10,96,277, 10, 400, 1100)
df<- data.frame(company,subsegment, values)

That's my code for the data frame and I try to make a grouped barchart:

plot.1<- ggplot(df, aes(fill=company, y=values, x=subsegment))   
  geom_bar(position="dodge", stat="identity", alpha=0.5)

The plot I get is exactly what I want, values for each company grouped by SubSegment... except the subsegments are ordered from left to right in default in alphabetical order "Sub1","Sub2","Sub3" and same for the companies...

I would like the same graphic to appear, but showing first "Sub3" then "Sub1" and last "Sub2" I would also like for the bars inside each group (inside each subsegment) to be ordered by value from bigger to smaller, instead of just alphabetically.

I attach picture of the graph I get: plot I get

Hope the question is clear enough, I want to get the same graph but change order of things in the x axis

CodePudding user response:

To reorder the subsegment, assign factor to it and specify the orders in levels.

To reorder the bars within dodged bar chart, use reorder to order the dodged bars with descending size of values.

library(tidyverse)

ggplot(df, aes(factor(subsegment, levels = c("Sub3", "Sub1", "Sub2")), 
               values, 
               fill = reorder(company, desc(values))))   
  geom_bar(position="dodge", stat="identity", alpha=0.5)  
  labs(x = "subsegment", fill = "company")

reorder_dodged_bar

CodePudding user response:

I did it by manipulating the underlying data. I like to do all my factor munging outside of the ggplot call; I think this makes things cleaner. Oh the joys of factors:

df<- data.frame(company,subsegment, values) %>%
  # subsegment order
  mutate(reorder_subsegment = case_when(
    subsegment == "Sub3" ~ 1,
    subsegment == "Sub1" ~ 2,
    subsegment == "Sub2" ~ 3
  )) %>% 
  mutate(subsegment = reorder(subsegment, reorder_subsegment)) %>% 
  # company order
  group_by(company) %>%
  mutate(company_by_value = sum(values)) %>%
  ungroup() %>% 
  mutate(company = reorder(company, -company_by_value))


ggplot(df, aes(fill=company, y=values, x=subsegment))   
  geom_col(position="dodge", alpha=0.5)
  • Related