我使用 R 語言對已知資料進行回歸分析/平滑。紅線為擬合回歸曲線,綠色背景為95%置信區間。現在我想按時間段為這張圖片中的紅線和綠色置信區間設定不同的顏色(2020年之前的紅色實線和灰色置信區間,2020年到2030年的綠色虛線和藍色置信區間),但我沒有知道如何設定代碼。
這是我的代碼。
data <- data.frame(
year = c(2003:2030),
number = c(40.84,49.2354,51.5988,53.9622,56.3256,64.79,61.0524,63.4158,65.7792,68.1426,76.4,72.8694,75.2328,77.5962,79.9596,76.36,71.99236,71.10268,70.39136,69.80928,69.31588,68.89523,68.53132,68.21586,67.93846,67.69439,67.47674,67.28291),
stringsAsFactors = FALSE
)
p3 <- ggplot(data, aes(x=year, y=number))
geom_point()
geom_smooth(method = lm, formula = y ~ splines::bs(x, 3), color="red", fill="#69b3a2", se=TRUE)
theme_ipsum()
p3
這個數字是我到目前為止繪制的。

這個數字是我最終想要的。

謝謝!!
uj5u.com熱心網友回復:
這是另一個嘗試:
library(tidyverse)
library(hrbrthemes)
data %>%
mutate(year_dich = ifelse(year<2015, "<2020", ">=2020")) %>%
ggplot(aes(x=year, y=number, group=year_dich))
geom_point()
geom_smooth(method = lm, formula = y ~ splines::bs(x, 3), se=TRUE,
aes(color = ifelse(data$year<2015, "red", "green"),
fill = ifelse(data$year<2015, "blue", "black"),
linetype = ifelse(data$year<2015, "dashed", "solid"))
)
theme_ipsum()
theme(legend.position = "none")

uj5u.com熱心網友回復:
通常人們試圖在 ggplot 中做太多事情——當你有非常具體的要求時,最好只計算出你想要繪制的內容,然后繪制它:
library(ggplot2)
library(hrbrthemes)
mod <- lm(formula = number ~ splines::bs(year, 3), data = data)
pred <- as.data.frame(predict(mod, se = TRUE)[1:2])
pred$year <- 2003:2030
pred$number <- pred$fit
pred$pre <- pred$year < 2020
ggplot(pred, aes(x=year, y=number))
geom_point(data = data)
geom_line(aes(color = pre, linetype = pre), size = 1.2)
geom_ribbon(aes(ymin = fit - 1.96 * se.fit, ymax = fit 1.96 * se.fit,
fill = pre), alpha = 0.2)
scale_fill_manual(values = c("dodgerblue", "gray"))
scale_color_manual(values = c("forestgreen", "red"))
scale_linetype_manual(values = c(2, 1))
theme_ipsum()
theme(legend.position = "none")

由reprex 包( v2.0.0 )于 2021 年 11 月 14 日創建
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/358890.html
