rggplot2geom-ribbon

Shade Area between crossing lines differently with ggplot


I would like to shade the area of the following plot with different colors. I would like to shade it in green to the right of the green line and red to its left.

I've already seen this similar question but I would like to do it in ggplot: Similar Question

#Break-even Chart
Q <- seq(0,50,1)
FC <- 50
P <- 7
VC <- 3.6
total_costs <- (FC + VC*Q)
total_revenues <- P*Q
BEP <- round(FC / (P-VC) + 0.5)

df_bep_chart <- as.data.frame(cbind(total_costs, total_revenues, Q))

ggplot(df_bep_chart, aes(Q, total_costs)) + 
  geom_line(group=1, size = 1, col="darkblue") + 
  geom_line(aes(Q, total_revenues), group=1, size = 1, col="darkblue") + 
  theme_bw() + 
  geom_ribbon(aes(ymin = total_revenues, ymax = total_costs), fill = "blue", alpha = .5) +
  geom_vline(aes(xintercept = BEP), col = "green") +
  geom_hline(aes(yintercept = FC), col = "red") +
  labs(title = "Break-Even Chart",
       subtitle = "BEP in Green, Fixed Costs in Red") + 
  xlab("Quanity") + 
  ylab("Money")

enter image description here


Solution

  • Try this. You have to condition the fill color on whether Q is on the left or on the right and use scale_fill_manual to set the fill colors:

    #Break-even Chart
    Q <- seq(0,50,1)
    FC <- 50
    P <- 7
    VC <- 3.6
    total_costs <- (FC + VC*Q)
    total_revenues <- P*Q
    BEP <- round(FC / (P-VC) + 0.5)
    
    df_bep_chart <- as.data.frame(cbind(total_costs, total_revenues, Q))
    
    library(ggplot2)
    
    ggplot(df_bep_chart, aes(Q, total_costs)) + 
      geom_line(group=1, size = 1, col="darkblue") + 
      geom_line(aes(Q, total_revenues), group=1, size = 1, col="darkblue") + 
      theme_bw() + 
      geom_ribbon(aes(ymin = total_revenues, ymax = total_costs, fill = ifelse(Q <= BEP, "red", "green")), alpha = .5) +
      scale_fill_manual(values = c(red = "red", green = "green")) +
      guides(fill = FALSE) +
      geom_vline(aes(xintercept = BEP), col = "green") +
      geom_hline(aes(yintercept = FC), col = "red") +
      labs(title = "Break-Even Chart",
           subtitle = "BEP in Green, Fixed Costs in Red") + 
      xlab("Quanity") + 
      ylab("Money")
    

    Created on 2020-06-16 by the reprex package (v0.3.0)