手动使用 ggplot2 的置信区间
Confidence interval using ggplot2 manually
我有一个包含四个变量的数据框。
(1) 表示期间的变量
(2) 估计值
(3) (1) 置信区间的上临界点
(4) (1)
置信区间的下临界点
具体我手动做了如下数据框
> my.dt <- data.frame(year = c(2017, 2018, 2019),
estimate = c(-20.866263, -29.28182, -33.37095),
up = c(-20.866263 + 2*4.159101, -29.28182 + 2*4.372621, -33.37095 + 2*4.707303),
down = c(-20.866263 - 2*4.159101, -29.28182 - 2*4.372621, -33.37095 - 2*4.707303))
> my.dt
year estimate up down
1 2017 -20.86626 -12.54806 -29.18446
2 2018 -29.28182 -20.53658 -38.02706
3 2019 -33.37095 -23.95634 -42.78556
在这里,我如何绘制(逐点)置信区间
如下所示:
这可以通过以下代码完成。你想使用 geom_errorbar :-)
ggplot(my.dt, aes(x=year, y=estimate)) +
geom_point(size = 5) +
geom_errorbar(aes(ymin = down, ymax = up))
同样的逻辑:稍作修改:
library(ggplot2)
ggplot(my.dt, aes(x = factor(year), y=estimate, color=factor(year))) +
geom_errorbar(aes(ymin = down, ymax = up), colour="black", width=.1, position=position_dodge(0.1)) +
geom_point(position=position_dodge(0.1), size=3, shape=15, fill="white") +
xlab("Year") +
ylab("Estimate") +
scale_colour_hue(name="Year",
breaks=c("2017", "2018", "2019"),
labels=c("2017", "2018", "2019"),
l=40) +
theme_classic() +
theme(aspect.ratio=2/3)
我有一个包含四个变量的数据框。 (1) 表示期间的变量 (2) 估计值 (3) (1) 置信区间的上临界点 (4) (1)
置信区间的下临界点具体我手动做了如下数据框
> my.dt <- data.frame(year = c(2017, 2018, 2019),
estimate = c(-20.866263, -29.28182, -33.37095),
up = c(-20.866263 + 2*4.159101, -29.28182 + 2*4.372621, -33.37095 + 2*4.707303),
down = c(-20.866263 - 2*4.159101, -29.28182 - 2*4.372621, -33.37095 - 2*4.707303))
> my.dt
year estimate up down
1 2017 -20.86626 -12.54806 -29.18446
2 2018 -29.28182 -20.53658 -38.02706
3 2019 -33.37095 -23.95634 -42.78556
在这里,我如何绘制(逐点)置信区间
如下所示:
这可以通过以下代码完成。你想使用 geom_errorbar :-)
ggplot(my.dt, aes(x=year, y=estimate)) +
geom_point(size = 5) +
geom_errorbar(aes(ymin = down, ymax = up))
同样的逻辑:稍作修改:
library(ggplot2)
ggplot(my.dt, aes(x = factor(year), y=estimate, color=factor(year))) +
geom_errorbar(aes(ymin = down, ymax = up), colour="black", width=.1, position=position_dodge(0.1)) +
geom_point(position=position_dodge(0.1), size=3, shape=15, fill="white") +
xlab("Year") +
ylab("Estimate") +
scale_colour_hue(name="Year",
breaks=c("2017", "2018", "2019"),
labels=c("2017", "2018", "2019"),
l=40) +
theme_classic() +
theme(aspect.ratio=2/3)