我正在尝试在此条形图中按顺序减小堆积条形图。我的问题是我的原始数据帧经历了相当多的操作,以便将它传递给我传递给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")
通常,我理解使用重新排序将一个变量的顺序层次更改为另一个变量,但在这种情况下,我实际上是在尝试将dTeam的顺序更改为每个dTeam的实例总数之后:
m %>%
group_by(Week, Pos) %>%
top_n(n = 5, wt = Points)
原始数据框的顶部供参考:
Team Week Name Opp. Points Salary Pos dTeam dSalary dPoints
1 ari 1 Palmer, Carson v. nor 28.68 6500 QB nor 2700 1
编辑: 我能够得到我想要的东西:
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")
我仍然想知道是否有更快/更简单的方法。