ggplot2-为折线图和条形图添加误差线

本文更新地址: ggplot2-为折线图和条形图添加误差线_ggplot 折线图 误差线-CSDN博客

本文在 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%置信区间的折线图
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

探索者v

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值