# 安装包
if (!requireNamespace("ggplot2", quietly = TRUE)) {
install.packages("ggplot2")
}if (!requireNamespace("Rmisc", quietly = TRUE)) {
install.packages("Rmisc")
}if (!requireNamespace("ggpubr", quietly = TRUE)) {
install.packages("ggpubr")
}
# 加载包
library(ggplot2)
library(Rmisc)
library(ggpubr)
误差线柱状图
带误差线和误差组的条形图。
环境配置
系统: Cross-platform (Linux/MacOS/Windows)
编程语言: R
依赖包:
ggplot2
;Rmisc
;ggpubr
数据准备
数据表:
第一列: (数值) Y 轴值。
第二列: (数值或字符串) X 轴类别。
# 加载数据
<- read.table("files/Hiplot/005-barplot-errorbar-data.txt", header = T)
data
# 整理数据格式
2] <- factor(data[, 2], levels = unique(data[, 2]))
data[, <- summarySE(data, measurevar = colnames(data)[1], groupvars = colnames(data)[2])
data_sd
# 查看数据
head(data_sd)
class N score sd se ci
1 math 4 63.50 3.109126 1.554563 4.947314
2 chinese 4 73.75 2.986079 1.493039 4.751518
3 english 4 83.25 2.362908 1.181454 3.759914
可视化
# 误差线柱状图
<- ggplot(data_sd, aes(x = data_sd[, 1], y = data_sd[, 3], fill = data_sd[, 1])) +
p geom_bar(stat = "identity", color = "black",
position = position_dodge(), alpha = 1) +
geom_errorbar(aes(ymin = data_sd[, 3] - sd, ymax = data_sd[, 3] + sd),
width = 0.2,
position = position_dodge(0.9)) +
labs(title = "Barplot (errorbar)", x = colnames(data_sd)[1],
y = colnames(data_sd)[3], fill = colnames(data_sd)[1]) +
geom_jitter(data = data, aes(data[, 2], data[, 1], fill = data[, 2]), size = 2, fill = "black", pch = 19, width = 0.2) +
stat_compare_means(data = data, aes(data[, 2], data[, 1], fill = data[, 2]),
label = "p.format", ref.group = ".all.", vjust = 1,
method = "t.test") +
scale_fill_manual(values = c("#E64B35FF","#4DBBD5FF","#00A087FF","#3C5488FF")) +
theme_bw() +
ylim(0,100) +
theme(text = element_text(family = "Arial"),
plot.title = element_text(size = 12,hjust = 0.5),
axis.title = element_text(size = 12),
axis.text = element_text(size = 10),
axis.text.x = element_text(angle = 0, hjust = 0.5,vjust = 1),
legend.position = "right",
legend.direction = "vertical",
legend.title = element_text(size = 10),
legend.text = element_text(size = 10))
p
