0

I am trying to order the stacked bars in this bar chart in decreasing size. My issue is that my original dataframe undergoes quite a few operations to get it to the one that I pass to ggplot():

m %>%
  group_by(Week, Pos) %>%
  top_n(n = 5, wt = Points) %>%
  ggplot(aes(x = dTeam)) +
  geom_bar(aes(fill = Pos), position = "stack") +
  xlab("Defensive Team") +
  ylab("Top 5 Weekly Scorers") +
  ggtitle("2015 DraftKings Total Top 5 Weekly Offensive Scorers per Defensive Team")

enter image description here Generally, I understand using reorder to change the order hierarchy of one variable to another, but in this case I'm actually trying to change the order of dTeam to the total number of instances of each dTeam after:

m %>%
  group_by(Week, Pos) %>%
  top_n(n = 5, wt = Points)

The top of the original dataframe for reference:

  Team Week           Name   Opp. Points Salary Pos dTeam dSalary dPoints
1  ari    1 Palmer, Carson v. nor  28.68   6500  QB   nor    2700       1

EDIT: I was able to get what I was looking for using this:

f <- m %>%
  group_by(Week, Pos) %>%
  top_n(n = 5, wt = Points)

f <- within(f, 
      dTeam <- factor(dTeam, 
          levels=names(sort(table(dTeam), 
              decreasing=TRUE))))
f %>%
  ggplot(aes(x = dTeam)) +
  geom_bar(aes(fill = Pos), position = "stack") +
  xlab("Defensive Team") +
  ylab("Top 5 Weekly Scorers") +
  ggtitle("2015 DraftKings Total Top 5 Weekly Offensive Scorers per Defensive Team")

I'm still wondering if there is a faster/easier way, though.

enter image description here

slothish1
  • 119
  • 1
  • 11
  • 1
    Did you try `reorder`? What happened? Consider adding a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) dataset rather than just a single line of your dataset. – aosmith Mar 25 '16 at 21:44
  • See my edit. I found an answer, but I'm still wondering if there might be an easier way? – slothish1 Mar 25 '16 at 22:14

0 Answers0