ggplot2 中的排序位置 "dodge"

Ordering position "dodge" in ggplot2

看起来很简单,但我找不到解决方案。

names(AllCoursesReg)
[1] "name"   "Course" "Status"

我的代码

ggplot(AllCoursesReg, aes(Course, fill = Status)) + 
geom_bar(aes(order = Status), position = "dodge", colour = "black") + theme_bw()+
guides(fill = guide_legend(reverse = TRUE)) 

我只想让注册人在左边,而不是在右边。 我已经尝试了 Order, level, factor,但它不起作用

感谢您的帮助。

您必须决定 factor 级别的顺序。这是来自 ?geom_bar.

的示例
# example from ?geom_bar
ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar(position="dodge")
# reorder cut using levels = rev(levels(cut))
ggplot(diamonds, aes(clarity, fill=factor(cut, levels = rev(levels(cut))))) + 
  geom_bar(position="dodge") + 
  scale_fill_discrete('cut') # change name back to cut

ggplot 自这个问题以来已经更新,所以这里的答案利用了 ggplot2 的新功能。

只需将 position_dodge2(reverse = TRUE) 添加到位置属性即可。使用 OP 的代码:

ggplot(AllCoursesReg, aes(Course, fill = Status)) + 
geom_bar(aes(order = Status), position=position_dodge2(reverse = TRUE), colour = "black") + theme_bw()+
guides(fill = guide_legend(reverse = TRUE))