我已经在ggplot中创建了一个堆积条形图。
antr1$Traits4<-factor(antr1$Traits4,
levels=c("Flight", "Avoidance", "Investigative",
"Defensive aggression","Active aggression"))
ggplot(antr1, aes(Receiver3, fill=Traits4)) +
geom_bar(position="fill") +
coord_flip() +
scale_y_continuous("", formatter="percent") +
scale_fill_manual(values=c("Flight"="yellow",
"Avoidance"="green",
"Investigative"="blue",
"Defensive aggression"="orange",
"Active aggression"="red"))
很好用。但是,此时根据“Receiver3”的名称按字母顺序排列条形。我想根据“主动攻击”等级的百分比重新排序堆积的栏。
提前感谢你
马特
答案 0 :(得分:3)
如果你知道你想要的Receiver3级别的顺序,你可以通过以下方式指定:
antr1$Receiver3 <- factor(antr1$Receiver3,
levels=c(...list the levels in the order you'd like...),
ordered=TRUE)
如果Receiver3有多个级别,那么手动确定正确的顺序是令人望而却步的,你可以尝试这样的事情:
temp <- aggregate(antr1$Traits4,by=list(receiver=antr1$Receiver3),
FUN=function(xx){
return(sum(xx=='Active aggression')/length(xx))
}
antr1$Receiver3 <- factor(antr1$Receiver3,levels=temp$receiver[order(temp$x)],
ordered=TRUE)
如果您想要相反的顺序,请将订单(temp $ x)更改为订单(temp $ x,减去= TRUE)。