Search code examples
rggplot2tidyversebar-chart

R - Issues with group order/ ggplot dodge barchart


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


Solution

  • 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