我需要基于两个带有填充的变量(points
和type
)制作条形图。
下面是一个最小的示例,我希望看到按 按后卫点排名 和 按后卫或前进点排名 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 Harden
和Klay
位居第三,{{1 }}排在第五位,Lebron
排在第六位,Kawhi
在底部。
如果按得分排序是后卫还是前锋,我希望看到KD
位于顶部,Lebron
其次,依此类推。
答案 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创建