How to fill geom_polygon with different colors above and below y = 0?

前端 未结 3 843
刺人心
刺人心 2020-11-27 21:06

Considering the following polygon plot:

ggplot(df, aes(x=year,y=afw)) +
  geom_polygon() +
  scale_x_continuous(\"\", expand=c(0,0), breaks=seq(1910,2010,10)         


        
3条回答
  •  北海茫月
    2020-11-27 21:51

    orig 
    
    orig_1 = orig
    orig_pos <- ifelse(orig_1$afw <= 0, 0, orig_1$afw) #positive when y >0
    
    orig_2 = orig
    orig_neg <- ifelse(orig2$afw > 0, 0, orig$afw) #negative when y<0
    
    
    df <- cbind.data.frame(orig, orig_neg, orig_pos) # dataframe of orig_neg < y < orig_pos
    
    ggplot(df)+
      geom_area(aes(year, orig_pos), fill = "blue") +
      geom_area(aes(year, orig_neg), fill = "red") +
      theme_bw()+
      scale_x_continuous("", expand=c(0,0), breaks=seq(1910,2010,10))
    

提交回复
热议问题