0

I am trying to reorder the bars (which each represent a categorical variable) in my R ggplot2 Note: I am not trying to reorder the percentages of variables represented within the bars.

This is what my bar chart looks like: What the stacked bar plot looks like

Most importantly, I want Enrollment on the top. Ideally, I would like this in reverse order (then Expulsion, then ISS, then OSS >1 day, then OSS 1 day)

Here is my code:

  ggplot(discbyracelong, 
       aes(x=discipline,
           y=pct, fill=Race))+ 
      geom_bar(stat="identity")+
      geom_text(aes(label=paste(round(pct,digits= 1),sep="")),
            position=position_stack(vjust=0.5),
            size= 3)+
      coord_flip()+
      guides(fill = guide_legend(reverse=TRUE))

Here is a link to my data: https://drive.google.com/file/d/14AwBBZfevTeZyrgwMpz7XwTj8J8pCUgO/view?usp=sharing

Thank you for any help!

Krista
  • 103
  • 7

2 Answers2

2

Just turn discipline into a factor. Instead of using unique, you could type out the values in a different order as well.

discbyracelong$discipline <- factor(discbyracelong$discipline, levels = (unique(discbyracelong$discipline)))

ggplot(discbyracelong, 
       aes(x=discipline,
           y=pct, fill=Race))+ 
  geom_bar(stat="identity")+
  geom_text(aes(label=paste(round(pct,digits= 1),sep="")),
            position=position_stack(vjust=0.5),
            size= 3)+
  coord_flip()+
  guides(fill = guide_legend(reverse=TRUE))

enter image description here

Qwfqwf
  • 483
  • 3
  • 9
  • That was easy! Thank you. I'm guessing I can do this for Race too. I'm still getting used to factors. I tried using them before to do this but my code must have been wrong. Thanks for the solution! – Krista Oct 26 '18 at 20:01
  • Glad it worked! You should be able to do it for Race also. Yeah ggplot2 is either super easy or super confusing for me, depending on what I'm trying to do. – Qwfqwf Oct 26 '18 at 20:53
0
scale_x_discrete(limits=c("Enrollment","Expulsion","In-School-Suspension", etc...))

see this link:http://www.sthda.com/english/wiki/ggplot2-axis-ticks-a-guide-to-customize-tick-marks-and-labels#change-the-order-of-items

bob1
  • 398
  • 3
  • 12