Search code examples
rdataframeggplot2plotfacet-wrap

How to reorder facet_wrap based on two variables


I need to make a bar plot based on two variables (points and type) with fill.

Below is a minimal example, I would like to see the points ranking by guard points and ranking by points as guard or forward.

I tried ~reorder(names, -c(type, points)) but it doesn't work.

    name <- c("James Harden","James Harden","Lebron James","Lebron James","Lebron James","Kawhi Leonerd","Kawhi Leonerd","Klay Thompson","Steph Curry","Kevin Durant","Kevin Durant","Chris Paul","Chris Paul")
    team <- c("HOU","OKC","LAL","MIA","CLE","SAS","TOR","GSW","GSW","GSW","OKC","HOU","LAC")
    points <- c(2000,12000,2000,10000,20000,7000,2000,14000,20000,6000,18000,4000,14000)
    type <- c("G","G","F","G","F","G","G","G","G","F","F","G","G")
    nba <- data.frame(name,team,points,type)
    nba <- nba %>% arrange(desc(type))
    ggplot(nba, aes(x = type, y = points, fill = team)) +
      geom_bar(stat = 'identity', position = 'stack', color = 'black') +
      facet_wrap(~reorder(name,-points),  ncol = 1, strip.position = "top") +
      coord_flip() + theme_minimal() +
      labs(x = "players", y = "points", title = "Rank by points as Guard")

If it's ranked by points as guard, I would like to see Steph Curry ranks top, Chris Paul at second, James Harden and Klay tied at third, Lebron at fifth, Kawhi at sixth, and KD at the bottom.

If it's ranked by points as either guard or forward, I'd like to see Lebron at top, KD second, so on and so forth.


Solution

  • You can sort it for points as guard by adding a helper column. Look below;

    library(ggplot2)
    library(dplyr)
    
    nba %>% 
     mutate(guardpoints = points * (type=="G")) %>% 
      ggplot(aes(x = type, y = points, fill = team)) +
      geom_bar(stat = 'identity', position = 'stack', color = 'black') +
      facet_wrap(~reorder(name, -guardpoints, sum),  ncol = 1, strip.position = "top") +
      coord_flip() + theme_minimal() +
      labs(x = "players", y = "points", title = "Rank by points as Guard")
    

    nba %>% 
      ggplot(aes(x = type, y = points, fill = team)) +
      geom_bar(stat = 'identity', position = 'stack', color = 'black') +
      facet_wrap(~reorder(name, -points, sum),  ncol = 1, strip.position = "top") +
      coord_flip() + theme_minimal() +
      labs(x = "players", y = "points", title = "Rank by points")
    

    Created on 2019-06-04 by the reprex package (v0.3.0)