使用ggplot以不同方式遮蔽交叉线之间的区域

Shade Area between crossing lines differently with ggplot

我想用不同的颜色遮蔽下图中的区域。我想在绿线右侧用绿色阴影,在左边用红色阴影。

我已经看过这个类似的问题,但我想在 ggplot 中这样做:

#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")

试试这个。您必须根据 Q 是在左侧还是右侧来调整填充颜色,并使用 scale_fill_manual 设置填充颜色:

#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")

reprex package (v0.3.0)

于 2020-06-16 创建