R语言ggplot按站点绘制分组均值丰度带误差棒柱状图咨询
分组柱状图实现方案
1. 数据结构转换
你当前使用的是宽格式数据,无法直接映射分组参数,需要先转为长格式:
library(tidyverse) # 宽表转长表,提取分组和均值丰度信息 DF_long <- DF %>% pivot_longer( cols = c(mol, an, crust, other), names_to = "group", # 生成分组列,对应mol/an/crust/other四类 values_to = "mean_abundance" # 生成均值丰度列,对应y轴数值 )
如果需要添加误差棒,先将所有分组的标准差数据整合后合并到数据表中:
# 构造标准差数据框,替换为你实际的各分组标准差数值 sd_df <- data.frame( Site = 1:5, mol = c(0.471404521, 0, 0, 5.656854249, 16.51934892), an = c(/* 替换为an组对应的5个站点标准差 */), crust = c(/* 替换为crust组对应的5个站点标准差 */), other = c(/* 替换为other组对应的5个站点标准差 */) ) %>% pivot_longer( cols = -Site, names_to = "group", values_to = "sd" ) # 合并均值与标准差数据 DF_final <- left_join(DF_long, sd_df, by = c("Site", "group"))
2. 绘图实现
转长格式后即可直接映射参数,解决你原来的参数填写问题:
ggplot(DF_final, aes(x = factor(Site), y = mean_abundance, fill = group)) + # 分组柱状图,dodge宽度设置为0.9方便和误差棒对齐 geom_bar(position = position_dodge(width = 0.9), stat = "identity") + # 误差棒,dodge宽度和柱状图保持一致避免错位 geom_errorbar( aes(ymin = mean_abundance - sd, ymax = mean_abundance + sd), width = 0.4, position = position_dodge(width = 0.9), colour = "orange", alpha = 0.9, size = 1 ) + # 轴标签与主题设置 labs(x = "站点", y = "均值丰度", fill = "分组类别") + theme(text = element_text(size = 20))
参数说明
x = factor(Site):将站点转为离散因子类型,避免x轴按连续数值展示出现异常间距fill = group:对应你需要的4个分组,自动按分组填充不同颜色y = mean_abundance:对应y轴的均值丰度数值
如果暂时不需要绘制误差棒,直接用DF_long替换代码中的DF_final,删除geom_errorbar部分代码即可正常出图。
内容的提问来源于stack exchange,提问作者Von Linné
相关产品推荐
相关产品推荐

