使用ggplot创建95%的置信区间

时间:2016-06-03 21:57:03

标签: r ggplot2

我无法使用ggplot绘制95%的置信区间。

这是我的代码:

> my.data
               scar response.rate
1               HTS          0.88
2               HTS          0.56
3               HTS          0.56
4               HTS          0.82
5               HTS          0.10
6               HTS          0.47
7               HTS          0.83
8               HTS          0.60
9            Linear          0.83
10           Linear          0.56
11           Linear          0.79
12           Linear          0.55
13           Linear          0.70
14           Linear          0.50
15           Keloid          1.00
16           Keloid          0.83
17           Keloid          1.00
18 Striae Distensae          0.33
19 Striae Distensae          0.33

ggplot(my.data, aes(scar, response.rate))+geom_point()+geom_smooth()

它产生的输出:

enter image description here

当我使用数字作为伤疤时,我能够产生以下内容:

enter image description here

我可以用疤痕类型而不是数字生成相同的图形吗?

1 个答案:

答案 0 :(得分:2)

此方法您手动创建CI,然后使用geom_errorbar()

绘制它们
library(ggplot2)
# Creating some data:
my.data = data.frame(c(rep("H",5),rep("L",5),rep("K",5),rep("S",5)), rnorm(20,1,.5) )
names(my.data) = c("scar", "response.rate")

# Standard error function
foo = function(x){sd(x)/sqrt(length(x))}

# Creating CI's manually
my.aggs = cbind(aggregate(response.rate ~ scar, data = my.data, FUN = foo),
                aggregate(response.rate ~ scar, data = my.data, FUN = mean))
names(my.aggs) = c("scar","se","","means")

# Plotting
ggplot()+
   geom_point(data = my.data, aes(as.factor(scar), response.rate)) +
   geom_errorbar(data = my.aggs, aes(scar, ymin=means-1.96*se, ymax=means+1.96*se), width=.1) 

# Alternative method that doesn't include points
library(gplots)
plotmeans(response.rate ~ scar, data = my.data)

enter image description here