本文在 Plotting means and error bars (ggplot2) 的基础上加入了自己的理解
采用ggplot2绘制折线图和条形图,并添加误差线.
ggplot2只能处理 data.frame数据,每列作为一个变量,是一个指标.
以ToothGrowth数据为例,进行处理
tg <- ToothGrowth
head(tg)
## len supp dose
## 1 4.2 VC 0.5
## 2 11.5 VC 0.5
## 3 7.3 VC 0.5
## 4 5.8 VC 0.5
## 5 6.4 VC 0.5
## 6 10.0 VC 0.5
library(ggplot2)
数据预处理
采用summarySE()
(函数定义在本文末尾)对数据进行预处理,计算数据的 标准误差(Standard Error). > 标准误差区别于标准差(Standard Deviation) . SE为 standard error of the mean 可以参考: 标准差(Standard Deviation) 和 标准误差(Standard Error)_标准值误差-CSDN博客
# summarySE 计算标准差和标准误差以及95%的置信区间.
tgc <- summarySE(tg, measurevar="len", groupvars=c("supp","dose"))
tgc
## supp dose N len sd se ci
## 1 OJ 0.5 10 13.23 4.459709 1.4102837 3.190283
## 2 OJ 1.0 10 22.70 3.910953 1.2367520 2.797727
## 3 OJ 2.0 10 26.06 2.655058 0.8396031 1.899314
## 4 VC 0.5 10 7.98 2.746634 0.8685620 1.964824
## 5 VC 1.0 10 16.77 2.515309 0.7954104 1.799343
## 6 VC 2.0 10 26.14 4.797731 1.5171757 3.432090
折线图
绘制带有误差线和95%置信区间线的折线图和点图
# 带有标准误差线的折线图
# Standard error of the mean
ggplot(tgc, aes(x=dose, y=len, colour=supp)) +
geom_errorbar(aes(ymin=len-se, ymax=len+se), width=.1) +
geom_line() +
geom_point()
# 对重叠的点,进行偏移处理(尽管这样可以将点分开便于观看,但是个人认为这并不科学)
pd <- position_dodge(0.1) # move them .05 to the left and right
ggplot(tgc, aes(x=dose, y=len, colour=supp)) +
geom_errorbar(aes(ymin=len-se, ymax=len+se), width=.1, position=pd) +
geom_line(position=pd) +
geom_point(position=pd)
## ymax not defined: adjusting position using y instead
## ymax not defined: adjusting position using y instead
# 绘制带有95%置信区间的折线图