在ggplot2中订购位置“躲避”

Moh*_*awy 5 r ggplot2

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

names(AllCoursesReg)
[1] "name"   "Course" "Status"
Run Code Online (Sandbox Code Playgroud)

我的代码

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

我只希望注册人在左边而不是右边。我已经尝试过顺序、级别、因子,但它不起作用

谢谢你的帮助。

在此处输入图片说明

小智 19

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)) 
Run Code Online (Sandbox Code Playgroud)

  • 这绝对是现在处理这个问题的最佳方式,其他选项都不适合我。 (2认同)

sha*_*dow 5

您必须决定 a 的级别顺序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
Run Code Online (Sandbox Code Playgroud)