如何在散点图中添加置信区间(R中的ggplot)

时间:2017-12-06 14:53:16

标签: r ggplot2

我想在分类变量的每个级别以及该图上的整个人口中显示因变量的90%RI间隔。对于vs = 0,disp变量的90%RI是200-250,vs = 1处的disp变量的RI是220-250,并且整个数据集的disp的CI是300-400。如何将这些间隔添加到此散点图中?

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"))

1 个答案:

答案 0 :(得分:2)

也许是这样的:

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

如果您有间隔,可以使用:

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