简体   繁体   中英

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!

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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM