简体   繁体   中英

Ordering position “dodge” in ggplot2

Seems simple but i couldnt find a solution.

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

My Code

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

I just want the Registrants to be on the left not on the right. I have tried Order, level, factor, and it is not working

Thanks for your help.

在此处输入图片说明

You have to decide on the ordering of the levels of a factor . Here's an example from ?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 has been updated since this question, so here's an answer that utilises a new feature from ggplot2.

Just add position_dodge2(reverse = TRUE) to the position attribute. Using OP's code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM