ggplot2: Changing the order of stacks on a bar graph

后端 未结 2 1251
有刺的猬
有刺的猬 2020-11-29 11:35

I\'m trying to make a stacked bar graph with a facet_wrap, but I want the order of my stacked variables (\"developed\") to be flipped. I\'ve reordered the factors, and trie

2条回答
  •  庸人自扰
    2020-11-29 11:41

    Fwiw, here is a solution with dplyr, and it uses scale_fill_manual to be explicit about the colors:

    library(ggplot2)
    library(dplyr)
    
    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)
    
    all_is2$agriculture=factor(all_is2$agriculture,levels=c("loi","dryland","agroforestry"))
    #all_is2$developed=factor(all_is2$developed,levels=c("available","developed"))
    
    all_is3 <- all_is2 %>% group_by(islands,agriculture,developed) %>% 
                           summarize(acres=sum(acres)) 
    
    ggplot(all_is3,aes(x=agriculture,y=acres,fill=developed))+
      geom_bar(position="stack", stat="identity")+
      facet_wrap(~islands)+ 
      xlab("")+ylab("Acres")+theme_bw() +
      scale_fill_manual(name="",values=c("available"="black","developed"="light gray"))
    

提交回复
热议问题