我在互聯網上到處搜索,但找不到問題的答案。我用 ggplot 繪制了一條帶有置信區間的平滑回歸線,但置信區域并未顯示為回歸線周圍的一條帶,而僅顯示在該線下方。這是圖形錯誤還是我錯過了正確的數學作為解釋?
我使用了以下代碼:
library(dplyr); library(ggplot2)
fig <-
df %>%
mutate(
Legend = case_when(
ind == "currentLifetimeRisk" ~ "Lifetime risk",
ind == "currentTenYearRisk" ~ "Ten year risk"
)
) %>%
ggplot(aes(x = age_measurements,
y = values,
fill=Legend))
geom_smooth(
aes(ymin = 0,
ymax = ..y..,),
alpha = 0.8,
formula = y ~ s(x, k = 9, bs="cs"),
color= "black", # kleur van de lijn
stat = "smooth",
method = "gam",
se = TRUE
)
scale_y_continuous(breaks = seq(0, 100, 25),
limits = c(0, 100), expand = c(0,0))
scale_x_continuous(breaks = seq(30, max(fig2_long$age_measurements), 10), expand = c(0,0))
theme(
axis.text =element_text(family = "sans", size=18,colour = "black"),
axis.title = element_text(size=18),
axis.line.x = element_line(size=0.5, linetype="solid", colour="black"),
axis.line.y = element_line(size=0.5, linetype="solid", colour="black"),
panel.grid.major = element_line(colour = "lightgrey"),
panel.background = element_blank(),
)
labs(
x = "Age at risk estimation",
y = "Risk of recurrent events (%)",
)
無花果
我希望將 95% 的置信區間視為回歸線周圍的一條帶,而不僅僅是在下面。非常感謝任何幫助。
uj5u.com熱心網友回復:
的用途aes(ymax=..y..)是強制置信區間的頂部等于由 計算的回歸線的擬合 y 值geom_smooth。如果洗掉aes(ymin = 0, ymax = ..y..),將繪制正確的置信區間。
..y..、..ymax..和..ymin..是內部計算的值geom_smooth,用于繪制回歸線和置信區間。設定ymax=..y..力geom_smooth以使用..y..(回歸的擬合 y 值)而不是..ymax..(計算的 95% 置信區間的頂部)作為圖中 95% 置信區間的頂部,從而導致您看到的問題。(我實際上不確定為什么ymin=0不強制 95% 置信區間的底部為零。)
洗掉aes映射(對于 不需要geom_smooth)會導致預期的置信區間繪圖。下面的示例重現了您看到的問題:
library(tidyverse)
library(patchwork)
p1 = mtcars %>%
ggplot(aes(mpg, hp, fill=factor(vs)))
geom_smooth(
aes(ymin=0, ymax = ..y..,),
alpha = 0.8,
formula = y ~ s(x, k=9, bs="cs"),
color= "black", # kleur van de lijn
stat = "smooth",
method = "gam",
se = TRUE
)
p2 = mtcars %>%
ggplot(aes(mpg, hp, fill=factor(vs)))
geom_smooth(
alpha = 0.8,
formula = y ~ s(x, k=9, bs="cs"),
color= "black", # kleur van de lijn
stat = "smooth",
method = "gam",
se = TRUE
)
p1 p2

由reprex 包于 2022-03-23 創建(v2.0.1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/450753.html
