你可以使用下面的基本语法在R语言中为条形图添加误差条:
ggplot(df) +
geom_bar(aes(x=x, y=y), stat='identity') +
geom_errorbar(aes(x=x, ymin=y-sd, ymax=y+sd), width=0.4)
下面的例子展示了如何在实践中使用这个函数。
例1:使用汇总数据添加误差条
假设我们在R语言中拥有以下数据框,显示了五个类别的汇总统计:
#create data frame
df <- data.frame(category=c('A', 'B', 'C', 'D', 'E'),
value=c(12, 17, 30, 22, 19),
sd=c(4, 5, 7, 4, 2))
#view data frame
df
category value sd
1 A 12 4
2 B 17 5
3 C 30 7
4 D 22 4
5 E 19 2
我们可以使用下面的代码来创建一个带有误差条的条形图,以使这个数据可视化:
library(ggplot2)
#create bar plot with error bars
ggplot(df) +
geom_bar(aes(x=category, y=value), stat='identity', fill='steelblue') +
geom_errorbar(aes(x=category, ymin=value-sd, ymax=value+sd), width=0.4)

请随意使用以下参数来修改误差条的外观。
- width: 误差条的宽度
- size: 误差条的大小,误差条的厚度
- color: 误差条的颜色
举例来说:
library(ggplot2)
#create bar plot with custom error bars
ggplot(df) +
geom_bar(aes(x=category, y=value), stat='identity', fill='steelblue') +
geom_errorbar(aes(x=category, ymin=value-sd, ymax=value+sd),
width=0.3, size=2.3, color='red')

例2:使用原始数据添加误差条
假设我们有以下数据框,显示了五个不同类别的原始数据:
#make this example reproducible
set.seed(0)
#create data frame
df <- data.frame(category=rep(c('A', 'B', 'C', 'D', 'E'), each=10),
value=runif(50, 10, 20))
#view first six rows of data frame
head(df)
category value
1 A 18.96697
2 A 12.65509
3 A 13.72124
4 A 15.72853
5 A 19.08208
6 A 12.01682
下面的代码显示了如何总结数据,然后创建一个带有误差条的条形图:
library(dplyr)
library(ggplot2)
#summarize mean and sd for each category
df_summary <- df %>%
group_by(category) %>%
summarize(mean=mean(value),
sd=sd(value))
#view summary data
df_summary
# A tibble: 5 x 3
category mean sd
1 A 16.4 2.80
2 B 14.9 2.99
3 C 14.6 3.25
4 D 15.2 2.48
5 E 15.8 2.41
#create bar plot with error bars
ggplot(df_summary) +
geom_bar(aes(x=category, y=mean), stat='identity', fill='steelblue') +
geom_errorbar(aes(x=category, ymin=mean-sd, ymax=mean+sd), width=0.3, color='red')

其他资源
下面的教程解释了如何在R中创建其他常见的数据可视化: