Tugrul Uzel Tugrul Uzel - 26 days ago 5
R Question

Ordering a 2 bar plot in R

I have a data set as below and I have created a graph with below code as suggested in a previous question. What I want to do is order the bars by rankings rather than team names. Is that possible to do in ggplot?

Team Names PLRankingsReverse Grreserve

Liverpool 20 20
Chelsea 19 19
Manchester City 15 18
Arsenal 16 17
Tottenham 18 16
Manchester United 8 15
Everton 10 14
Watford 13 13
Burnley 17 12
Southampton 9 11
WBA 11 10
Stoke 4 9
Bournemouth 12 8
Leicester 7 7
Middlesbrough 14 6
C. Palace 6 5
West Ham 1 4
Hull 3 3
Swansea 5 2
Sunderland 2 1


And here is the code:

alldata <- read.csv("premierleague.csv")
library(ggplot2)
library(reshape2)
alldata <- melt(alldata)
ggplot(alldata, aes(x = Team.Names, y= value, fill = variable), xlab="Team Names") +
geom_bar(stat="identity", width=.5, position = "dodge")


Thanks for the help!

Answer

In this case you need to sort your data frame prior to melting and capture the order. You can then use this to set the limit order on scale_x_discrete, or you can factor Team Name in your aes string.

Using factor:

ordr <- order(alldata$`Team Names`, alldata$PLRankingsReverse, decreasing = TRUE)

alldata <- melt(alldata)

ggplot(alldata, aes(x = factor(`Team Name`, ordr),  y = value, fill = variable) + 
  labs(x = "Team Name") +
  geom_bar(stat = "identity", width = .5, position = "dodge") 

Using scale_x_discrete:

ordr <- alldata$`Team Name`[order(alldata$PLRankingsReverse, decreasing = TRUE)]

alldata <- melt(alldata)

ggplot(alldata, aes(x = `Team Name`, y = value, fill = variable) + 
  labs(x = "Team Name") +
  geom_bar(stat = "identity", width =. 5, position = "dodge") +
  scale_x_discrete(limits = ordr)