Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering position "dodge" in ggplot2

Tags:

r

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.

enter image description here

like image 364
Mohammad Zahrawy Avatar asked Mar 13 '15 15:03

Mohammad Zahrawy


People also ask

What does position Dodge do in ggplot2?

Dodging preserves the vertical position of an geom while adjusting the horizontal position. position_dodge() requires the grouping variable to be be specified in the global or geom_* layer. Unlike position_dodge() , position_dodge2() works without a grouping variable in a layer.

How do I reorder ggplot2?

To reorder the boxplot we will use reorder() function of ggplot2. By default, ggplot2 orders the groups in alphabetical order. But for better visualization of data sometimes we need to reorder them in increasing and decreasing order. This is where the reorder() function comes into play.


2 Answers

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)) 
like image 159
JamesR Avatar answered Sep 29 '22 11:09

JamesR


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
like image 33
shadow Avatar answered Sep 29 '22 13:09

shadow