感謝您對以下問題的幫助。
我正在嘗試將 95% Credival Intervals(這與置信區間不同)添加到按源分隔的密度圖中。
計算 95% CI 的最佳方法是使用函式hdi(x, ci = 0.95)
('HDInterval' 包)。
我想在 中制作情節ggplot()
,因為它更容易操作。
以下是一些模擬資料:
set.seed(14)
df <- data.frame(density = c(rgamma(400, 2, 10), rgamma(400, 2.25, 9),rgamma(400, 5, 7)),
source = rep(c("source_1", "source_2", "source_3"),
each = 400))
對于 ggplot
ggplot(df, aes(x = density, color = source))
geom_density(size=1.5, alpha = 0.4)
labs(y = "Density", x = "Source contribution")
以及填充區域代表 95% CI 的圖。
我還分別計算了上下 95% CI。
S1 <- df %>% filter(df$source == "source_1")
S2 <- df %>% filter(df$source == "source_2")
S3 <- df %>% filter(df$source == "source_3")
data_lower <- tribble(~source, ~value, ~hdi,
'S1' , 0.025, hdi(S1$density)["lower"],
'S2' , 0.025, hdi(S2$density)["lower"],
'S3' , 0.025, hdi(S3$density)["lower"])
data_upper <- tribble(~source, ~value, ~hdi,
's1', 0.975, hdi(S1$density)["upper"],
's2', 0.975, hdi(S2$density)["upper"],
's3', 0.975, hdi(S3$density)["upper"])
但它們也可以按源計算。
hdi(S1$density, ci = 0.95)
hdi(S2$density, ci = 0.95)
hdi(S3$density, ci = 0.95)
我會很感激你的幫助。提前致謝。
uj5u.com熱心網友回復:
將@ClausWilke的這個答案改編為您的案例,您可以通過ggridges:: geom_density_ridges_gradient
. 基本上我使用after_stat
andifelse
來填充由hdi
.
set.seed(14)
df <- data.frame(
density = c(rgamma(400, 2, 10), rgamma(400, 2.25, 9), rgamma(400, 5, 7)),
source = rep(c("source_1", "source_2", "source_3"),
each = 400
)
)
library(ggplot2)
library(HDInterval)
library(ggridges)
ggplot(df, aes(x = density, color = source, fill = after_stat(ifelse(quantile == 2, NA, color))))
geom_density_ridges_gradient(aes(y = 0), quantile_lines = TRUE, quantile_fun = hdi, vline_linetype = 0)
labs(y = "Density", x = "Source contribution")
scale_fill_discrete(guide = "none", na.value = "transparent")
#> Picking joint bandwidth of 0.0546
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/498304.html