如何基于两个变量重新排序facet_wrap

时间:2019-06-04 17:38:51

标签: r dataframe ggplot2 plot facet-wrap

我需要基于两个带有填充的变量(pointstype)制作条形图。

下面是一个最小的示例,我希望看到按 按后卫点排名 按后卫或前进点排名 em> 。

我尝试了~reorder(names, -c(type, points)),但是没有用。

    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")

如果按得分排名后卫,我希望看到Steph Curry位居第一,Chris Paul位居第二,James HardenKlay位居第三,{{1 }}排在第五位,Lebron排在第六位,Kawhi在底部。

如果按得分排序是后卫还是前锋,我希望看到KD位于顶部,Lebron其次,依此类推。

1 个答案:

答案 0 :(得分:1)

您可以通过添加帮助者列将其作为守卫进行排序。看下面;

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")

reprex package(v0.3.0)于2019-06-04创建