M.C. Park
M.C. Park

Reputation: 305

Confidence interval using ggplot2 manually

I have a data frame that contains four variables. (1) a variable indicating the period (2) estimates values (3) upper critical point of the confidence interval of (1) (4) lower critical point of the confidence interval of (1)

Specifically, I manually made the following data frame

> 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

Here, how can I draw (pointwise) confidence interval like below: enter image description here

Upvotes: 3

Views: 2918

Answers (2)

TarJae
TarJae

Reputation: 78927

Same logic: Slightly modified:

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)

enter image description here

Upvotes: 2

hikren
hikren

Reputation: 148

This can be done with the following code. You want to use geom_errorbar :-)

ggplot(my.dt, aes(x=year, y=estimate)) +         
       geom_point(size = 5) +
       geom_errorbar(aes(ymin = down, ymax = up))

enter image description here

Upvotes: 4

Related Questions