Search code examples
rggplot2boxplotribbon

How to use the ribbon tool in ggplot2 to fill between two geom h_lines


So I've got barcharts with hlines on at the moment to show legal limits for nutrient concentrations but I want these limits to show as faded blocks behind the plot if that makes sense? For example, for the h_line at 0.173 I want a yellow band between 0.069 and 0.173 instead. Is this possible? If so please advise! - I'm pretty new to R

Thanks in advance!

#Primary phosphate
primary.P<-c(0.105,0.104,0.106,0.099,0.1,0.095)

groupP<-c("A","B","C","D","E","F")

sdP<-c(0.004,0.004,0.004,0.004,0.004,0.004)
p.p.dataframe<-data.frame(primary.P,groupP,sdP,stringsAsFactors=FALSE)  
#the plot
ggplot(p.p.dataframe)+
  geom_bar( aes(x=groupP, y=primary.P), stat="identity", fill="darkgrey", alpha=0.5) +
  labs(y=expression(bold(Phosphate~"("*mg~N~L^-1*")")), x=expression(bold("Group")))+
  geom_errorbar( aes(x=group, ymin=primary.P-sdP, ymax=primary.P+sdP), width=0.4, colour="orange", alpha=0.9, size=1.3)+
  #adding ablines 
  geom_hline(yintercept = 0.173, col="yellow")+
  geom_hline(yintercept = 0.069, col="")+
  geom_hline(yintercept = 0.036, col="green")+
  geom_hline(yintercept = 0.102, col="black", lwd=1, linetype=2)+
  theme_classic()

Solution

  • Try this. You can add a yellow band via geom_rect:

    library(ggplot2)
    
    primary.P<-c(0.105,0.104,0.106,0.099,0.1,0.095)
    
    groupP<-c("A","B","C","D","E","F")
    
    sdP<-c(0.004,0.004,0.004,0.004,0.004,0.004)
    p.p.dataframe<-data.frame(primary.P,groupP,sdP,stringsAsFactors=FALSE)  
    #the plot
    ggplot(p.p.dataframe)+
      # Yellow band with transparency alpha = .1
      # "dummy_yellow" is just a dummy name.
      geom_rect(aes(fill = "dummy_yellow"), xmin = 0, xmax = 10, ymin = 0.069, ymax = 0.173, alpha = .1)+
      geom_rect(aes(fill = "dummy_green"), xmin = 0, xmax = 10, ymin = 0, ymax = 0.036, alpha = .1)+
      geom_bar(aes(x=groupP, y=primary.P), stat="identity", fill="darkgrey", alpha=0.5) +
      labs(y=expression(bold(Phosphate~"("*mg~N~L^-1*")")), x=expression(bold("Group")))+
      geom_errorbar( aes(x=groupP, ymin=primary.P-sdP, ymax=primary.P+sdP), width=0.4, colour="orange", alpha=0.9, size=1.3)+
      #adding ablines 
      geom_hline(yintercept = 0.173, col="yellow")+
      geom_hline(yintercept = 0.069, col="transparent")+
      geom_hline(yintercept = 0.036, col="green")+
      geom_hline(yintercept = 0.102, col="black", lwd=1, linetype=2) +
      # Here we assign to dummy_yellow the fill color "yellow" 
      scale_fill_manual(name = "colored bands", values = c(dummy_yellow = "yellow", dummy_green = "green")) +
      theme_classic()
    

    Created on 2020-03-31 by the reprex package (v0.3.0)