user8322300
user8322300

Reputation: 77

How to add the confidence interval in scatter plot (ggplot in R)

I want to show the 90%RI intervals of the dependent variable at each level of the categorical variable and also the whole population on this plot. The 90%RI for disp variable at vs=0 is 200-250, the RI for disp variable at vs=1 is 220-250, and the CI for disp for whole data set is 300-400. How can I add these intervals into this scatter plot?

ggplot(mtcars, aes(mpg, disp)) + 
      geom_point(aes(colour=factor(vs), 
      fill = factor(vs)), shape=21, size = 4) + 
  scale_fill_manual(values=c("blue", "pink")) + 
  scale_colour_manual(values=c("black", "black"))

Upvotes: 2

Views: 2640

Answers (1)

Axeman
Axeman

Reputation: 35242

Perhaps something like:

ggplot(mtcars, aes(mpg, disp, colour = factor(vs), fill = factor(vs))) + 
  geom_point(shape = 21, size = 4, col = "black") + 
  stat_summary(aes(vs+8, disp, col = factor(vs)), 
               fun.data = function(x) mean_cl_normal(x, conf.int = 0.9)) +
  stat_summary(aes(7, disp, group = 1), 
               fun.data = function(x) mean_cl_normal(x, conf.int = 0.9))

enter image description here

If you have intervals, you could use:

cis <- data.frame(vs = c(0, 1, 'all'), lwr = c(200, 220, 300), upr = c(250, 250, 400))
ggplot(mtcars, aes(colour = factor(vs), fill = factor(vs))) + 
  geom_point(aes(mpg, disp), shape = 21, size = 4, col = "black") +
  geom_linerange(aes(x = c(8:10), ymin = lwr, ymax = upr), cis)

enter image description here

Upvotes: 2

Related Questions