绘制分组柱状图;柱状图上添加误差线;组内柱子之间添加显著性差异表示(字母表示)。
大概思路是首先绘制分组柱形图,然后利用 geom_errorbar 和 geom_text 直接添加;因为柱形图使用的是单个数据绘制,所以标准差以及差异是否显著就在 R 语言之外进行计算,而后整合进表格进行读取。
示例文件将标准差写进表格中了,差异是否显著也可以仿照标准差写进表格。具体见以下代码:
library(ggplot2)
library(reshape2)
# 创建示例数据集
data <- data.frame(
Category = c("A", "B", "C", "D", "E"),
Value1 = c(23, 45, 56, 78, 34),
Value2 = c(32, 54, 65, 82, 45),
Value1_sd = c(5, 4, 6, 7, 5),
Value2_sd = c(4, 6, 5, 8, 4)
)
# 将数据转换成适合 ggplot2 的长格式,同时保留标准差信息
data_long <- melt(data, id.vars = c("Category", "Value1_sd", "Value2_sd"), variable.name = "Variable")
# 使用 ggplot2 创建分组柱状图
p <- ggplot(data_long, aes(x = Category, y = value, fill = Variable)) +
geom_bar(stat = "identity", position = "dodge") +
labs(title = "分组柱状图示例", x = "类别", y = "值", fill = "变量")
# 添加误差条
p + geom_errorbar(aes(ymin = value - ifelse(Variable == "Value1", Value1_sd, Value2_sd),
ymax = value + ifelse(Variable == "Value1", Value1_sd, Value2_sd)),
position = position_dodge(width = 0.9), width = 0.25)
p + geom_errorbar(aes(ymin = value - ifelse(Variable == "Value1", Value1_sd, Value2_sd),
ymax = value + ifelse(Variable == "Value1", Value1_sd, Value2_sd)),
position = position_dodge(width = 0.9), width = 0.25) +
geom_text(aes(label = ifelse(Variable == "Value1", "a", "b")),
position = position_dodge(width = 0.9), vjust = -0.5)
类似的,贴一个自己的数据写的命令,有一些参数可供参考。
ggplot(x, aes(x = Trait, y = Index, fill = Zone)) +
geom_bar(stat = "identity", position = "dodge") +
geom_errorbar(aes(ymin = Index, ymax =Index + SD), width = 0.2, position = position_dodge(0.9)) +
geom_text(aes(label = Significance, y = Index + SD), position = position_dodge(width = 0.9), vjust = -0.5)
大概就是这个意思,其余细节有待进一步调整美化。
网友评论