[英]Add Credible Intervals to each line
I would appreciate your help with the following issue.感谢您对以下问题的帮助。
I am trying to add the 95% Credival Intervals (this is not the same as Confidence Intervals) to a density plot, which is separated by source.我正在尝试将 95% Credival Intervals(这与置信区间不同)添加到按源分隔的密度图中。
The best way to calculate the 95% CI is with the function hdi(x, ci = 0.95)
('HDInterval' package).计算 95% CI 的最佳方法是使用函数
hdi(x, ci = 0.95)
('HDInterval' 包)。
I would like to make the plot in ggplot()
, because it is easier to manipulate.我想在
ggplot()
中制作情节,因为它更容易操作。
Here are some simulated data:以下是一些模拟数据:
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))
For the ggplot对于 ggplot
ggplot(df, aes(x = density, color = source)) +
geom_density(size=1.5, alpha = 0.4) +
labs(y = "Density", x = "Source contribution")
And the plot where the filled areas represent the 95% CI.以及填充区域代表 95% CI 的图。
I also calculated the lower and upper 95% CI individually.我还分别计算了上下 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"])
But they can also be calculated by source.但它们也可以按源计算。
hdi(S1$density, ci = 0.95)
hdi(S2$density, ci = 0.95)
hdi(S3$density, ci = 0.95)
I would appreciate your help.我会很感激你的帮助。 Thanks in advance.
提前致谢。
Adapting this answer by @ClausWilke to your case you could achieve your result via ggridges:: geom_density_ridges_gradient
.将@ClausWilke 的这个答案改编为您的案例,您可以通过
ggridges:: geom_density_ridges_gradient
实现您的结果。 Basically I use after_stat
and an ifelse
to fill only the upper and lower quantiles computed by hdi
.基本上,我使用
after_stat
和ifelse
仅填充由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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.