[英]plotting threshold/piecewise/change point models with 95% confidence intervals in R
我想 plot 閾值 model 線段之間具有平滑的 95% 置信區間線。 您會認為這很簡單,但我一直無法找到答案!
我的閾值/斷點是已知的,如果有辦法可視化這些數據,那就太好了。 我嘗試了分段的 package,它產生以下 plot:
plot 顯示閾值 model,斷點為 5.4。 但是,回歸線之間的置信區間並不平滑。
如果有人知道在分段回歸線(理想情況下在 ggplot 中)之間產生平滑(即沒有線段之間的跳躍)CI 線的任何方法,那將是驚人的。 太感謝了。
我已經包含了示例數據和我在下面嘗試過的代碼:
x <- c(2.26, 1.95, 1.59, 1.81, 2.01, 1.63, 1.62, 1.19, 1.41, 1.35, 1.32, 1.52, 1.10, 1.12, 1.11, 1.14, 1.23, 1.05, 0.95, 1.30, 0.79,
0.81, 1.15, 1.10, 1.29, 0.97, 1.05, 1.05, 0.84, 0.64, 0.80, 0.81, 0.61, 0.71, 0.75, 0.30, 0.30, 0.49, 1.13, 0.55, 0.77, 0.51,
0.67, 0.43, 1.11, 0.29, 0.36, 0.57, 0.02, 0.22, 3.18, 3.79, 2.49, 2.44, 2.12, 2.45, 3.22, 3.44, 3.86, 3.53, 3.13)
y <- c(22.37, 18.93, 16.99, 15.65, 14.62, 13.79, 13.09, 12.49, 11.95, 11.48, 11.05, 10.66, 10.30, 9.96, 9.65, 9.35, 9.07, 8.81,
8.56, 8.32, 8.09, 7.87, 7.65, 7.45, 7.25, 7.05, 6.86, 6.68, 6.50, 6.32, 6.15, 5.97, 5.80, 5.63, 5.47, 5.30,
5.13, 4.96, 4.80, 4.63, 4.45, 4.28, 4.09, 3.90, 3.71, 3.50, 3.27, 3.01, 2.70, 2.28, 22.37, 16.99, 11.05, 8.81,
8.56, 8.32, 7.25, 7.05, 6.50, 6.15, 5.63)
lin.mod <- lm(y ~ x)
segmented.mod <- segmented(lin.mod, seg.Z = ~x, psi=2)
plot(x, y)
plot(segmented.mod, add=TRUE, conf.level = 0.95)
這會產生以下 plot (以及 95% 置信區間的相關跳躍):
背景:現有變更點包中的不平滑是由於常客包以固定的變更點值運行的事實。 但與所有推斷的參數一樣,這是錯誤的,因為變化的位置確實存在不確定性。
解決方案: AFAIK,只有貝葉斯方法可以量化它,而mcp
package 填補了這個空間。
library(mcp)
model = list(
y ~ 1 + x, # Segment 1: Intercept and slope
~ 0 + x # Segment 2: Joined slope (no intercept change)
)
fit = mcp(model, data = data.frame(x, y))
默認 plot ( plot.mcpfit()
返回一個ggplot
對象):
plot(fit) + ggtitle("Default plot")
每條線代表一個可能的 model 生成數據。 變化點的后驗顯示為藍色密度。 您可以單獨使用plot(fit, q_fit = TRUE)
或 plot 在頂部添加一個可信區間:
plot(fit, lines = 0, q_fit = c(0.025, 0.975), cp_dens = FALSE) + ggtitle("Credible interval only")
如果您的更改點確實已知並且您想要 model 每個段的不同剩余比例(即,准模擬segmented
),您可以執行以下操作:
model2 = list(
y ~ 1 + x,
~ 0 + x + sigma(1) # Add intercept change in residual scale
)
fit = mcp(model2, df, prior = list(cp_1 = 1.9)) # Note: prior is a fixed value - not a distribution.
plot(fit, q_fit = TRUE, cp_dens = FALSE)
請注意,CI 不會像segmented
那樣圍繞更改點“跳躍”。 我相信這是正確的行為。 披露:我是mcp
的作者。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.