首页 > 解决方案 > ggplot在barplot中更改堆栈顺序

问题描述

我有以下情节,我需要将蓝条(失败)置于顶部。我试过了,order但没有做出预期的改变。订单有什么问题?

ggplot(a, aes(fill=Var1, y=value, x=Var2, order("pass","fail"))) 
       +geom_bar( stat="identity", position="fill") + labs(x = "Subject", y="Pass/Fail Percentage") 
       + guides(fill=guide_legend(title="Result"))

在此处输入图像描述

这是我的数据

Var1    Var2    value
pass    Maths   865     
fail    Maths   135     
pass    Reading 910     
fail    Reading 90      
pass    Writing 886     
fail    Writing 114

标签: r

解决方案


我建议重新调整因子,像这样。

a %>% mutate(Var1 = factor(Var1, levels = c("fail", "pass"))) %>%
  ggplot(aes(fill=Var1, y=value, x=Var2)) + 
  geom_bar( stat="identity", position="fill") + labs(x = "Subject", y="Pass/Fail Percentage") + 
  guides(fill=guide_legend(title="Result"))

在此处输入图像描述


推荐阅读