[英]Shade Area between crossing lines differently with ggplot
我想用不同的 colors 對以下 plot 的區域進行着色。 我想在綠線的右邊用綠色遮住它,在它的左邊用紅色遮住它。
我已經看過這個類似的問題,但我想在 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
設置填充 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")
由代表 package (v0.3.0) 於 2020 年 6 月 16 日創建
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.