如何使用ggplot对R中的每个分组条重新排序?

时间:2018-10-26 19:46:29

标签: r ggplot2

我正在尝试对R ggplot2中的条形图(每个代表一个类别变量)进行重新排序。注意:我并不是要对条形图中所代表的变量的百分比进行重新排序。

这是我的条形图的样子: What the stacked bar plot looks like

最重要的是,我希望“注册”位于顶部。理想情况下,我想按相反的顺序(然后是驱逐,然后是ISS,然后是OSS> 1天,然后是OSS 1天)

这是我的代码:

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

以下是我的数据链接:https://drive.google.com/file/d/14AwBBZfevTeZyrgwMpz7XwTj8J8pCUgO/view?usp=sharing

谢谢您的帮助!

2 个答案:

答案 0 :(得分:2)

只需将discipline变成一个因子。除了使用unique,您还可以按其他顺序键入值。

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

答案 1 :(得分:0)

scale_x_discrete(limits=c("Enrollment","Expulsion","In-School-Suspension", etc...))

查看此链接:http://www.sthda.com/english/wiki/ggplot2-axis-ticks-a-guide-to-customize-tick-marks-and-labels#change-the-order-of-items