ggplot ordering a clustered barplot

Viewed 44

Code to reproduce the issue I have:

library("data.table")
library("ggplot2")
DT<-data.table(team=c("Q1","Q2","Q3"), mon=c(3,5,2), tues=c(4,2,1), weds=c(4,2,5))
DT<-melt(DT,id.vars = "team", measure.name = c("mon","tues","weds"))
chartdata<-DT[,.(team, day=variable, score=value)]
ggplot(chartdata, aes(fill=day, y=score, x=team)) +#reorder(data3$Insurer, if(thisdir=="asc") {value} else {-value}))) + 
  geom_bar(position="dodge", stat="identity") 

This produces a clustered barplot. I need to set the order by Monday's score (descending), but can't see a way of doing this. I have tried:

ggplot(chartdata, aes(fill=day, y=score, x=reorder(team, {-score}))) + 
  geom_bar(position="dodge", stat="identity") 

but this appears to sort the data measured by the totals of Monday - Wedsnesday, not using only Monday as I want.

Is this possible? Many thanks!

1 Answers

You can sort your dataframe before plotting into ggplot2 and fix factor levels of the variable used for x axis:

library(dplyr)
library(ggplot2)

chartdata %>% 
  arrange(day, -score) %>% 
  mutate(team = factor(team, unique(team))) %>%
  ggplot(aes(x = team, y = score, fill = day))+
  geom_col(position = position_dodge())

enter image description here

Is it what you are looking for ?

Related