复制图表时使用GGsignif遇‘均值未找到’报错的解决方法
解决GGsignif添加显著性括号时“均值未找到”的报错
核心错误原因
geom_signif的data参数错误:你传入了df$Genotype(单个因子向量),但该图层需要包含显著性标注信息的数据框,应使用你预先处理好的Realtionship.test。xmin/xmax参数不匹配当前x轴映射:你的ggplot x轴是Rac-GR24(因子类型,取值为0 μM/10 μM),同时用position_dodge(0.6)实现分组,不能直接用Protein_genotype的字符串作为x位置,需对应x轴的数值位置加上偏移量。- 参数关联混乱:
annotations等参数未正确关联到Realtionship.test中的对应列。
修正后的代码
第一步:补充缺失的原始数据预处理(解决MutatedData未定义问题)
假设Raw_data就是t_test中用到的Relative Expression列,先整理数据:
# 补全MutatedData的定义 MutatedData <- df %>% rename(`Relative Expression` = Raw_data, Protein_Genotype = Protein_genotype)
第二步:修正geom_signif图层
替换数据源并正确计算x轴位置,匹配分组偏移:
Plot <- ggplot(data = df, aes(y = Mean, x = `Rac-GR24`, fill = Genotype, width = 0.4))+ geom_bar(stat = "identity", colour="black", width = 1.4, position = position_dodge(width = 0.6))+ geom_jitter(aes(y = Raw_data, x = `Rac-GR24`), size = 0.5, fill = NA, pch = 21, stroke = 1.3, position = position_nudge(x=df$nudge_amount)) + geom_errorbar(aes(ymax=Mean+SE, ymin=Mean-SE), width=0.4, colour="black", position = position_dodge(0.6))+ # 修正后的显著性标注图层 geom_signif(data = Realtionship.test, aes(xmin = case_when(Rac.GR24 == "0 μM" ~ 1 - 0.3, Rac.GR24 == "10 μM" ~ 2 - 0.3), xmax = case_when(Rac.GR24 == "0 μM" ~ 1 + 0.3, Rac.GR24 == "10 μM" ~ 2 + 0.3), y_position = y.position, annotations = Labels), manual = TRUE, inherit.aes = FALSE, textsize = 1, size=0.5)
额外注意事项
- 确保你定义的
average_*和SE_*变量真实存在,否则df中的Mean和SE列会生成NA,也会触发“均值未找到”类错误。 position_dodge的宽度要和geom_bar中保持一致(此处为0.6),偏移量设为±0.3(宽度的一半),才能精准对应WT和NSs柱子的位置。- 带连字符的列名
Rac-GR24在ggplot中需用反引号`Rac-GR24`包裹,避免语法错误。
内容的提问来源于stack exchange,提问作者Corey Avis
相关产品推荐
相关产品推荐

