小编Nat*_*e K的帖子

ggplot2:更改条形图上的堆栈顺序

我正在尝试使用facet_wrap创建一个堆积条形图,但我想要翻转我的堆叠变量("已开发")的顺序.我已经重新排序了这些因素,并尝试了"order = descend()"以及"scale_fill_manual",似乎没有任何效果.

这是我的代码:

developed=rep(c("developed","available"),6)
agriculture=rep(c(rep("loi",2), rep("dryland",2), rep("agroforestry",2)),2)  
acres=c(7435,24254,10609,120500,10651,75606,6037,9910,4390,895,9747,46893)
islands=c(rep("All islands",6), rep("Oahu",6))
all_is2=data.frame(developed, agriculture, acres, islands)
head(all_is2)
  developed  agriculture  acres      island
1 developed          loi   7435 All islands
2 available          loi  24254 All islands
3 developed      dryland  10609 All islands
4 available      dryland 120500 All islands
5 developed agroforestry  10651 All islands
6 available agroforestry  75606 All islands
Run Code Online (Sandbox Code Playgroud)

改变"农业"和"发达"的因素水平

all_is2$agriculture=factor(all_is2$agriculture,levels=c("loi","dryland","agroforestry"))
all_is2$developed=factor(all_is2$developed,levels=c("developed","available"))
levels(all_is2$developed)
[1] "developed" "available"
Run Code Online (Sandbox Code Playgroud)

然后,绘图:

ggplot(all_is2,aes(x=agriculture,y=acres,fill=developed))+
     geom_bar(position="stack", stat="identity")+
     facet_wrap(~islands)+ scale_fill_grey(start=0.8, end=0.2, name="")+ xlab("")+ylab("Acres")+theme_bw()+ scale_y_continuous(labels=comma)
Run Code Online (Sandbox Code Playgroud)

图表

我希望条形图的"开发"部分是灰色的,在条形图的"可用"部分的顶部是黑色的.并且图例也应该与条形的顺序相匹配.

此外,是否可以将facet_wrap"All islands"和"Oahu"移动到图表底部的"loi""dryland"和"agroforestry"下.谢谢您的帮助!!

r ggplot2 facet-wrap stacked-chart

12
推荐指数
1
解决办法
4376
查看次数

标签 统计

facet-wrap ×1

ggplot2 ×1

r ×1

stacked-chart ×1