You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改ggplot2中geom_signif显著性条的颜色

问题原因

你将colour = Hours参数放在了ggplot()的全局美学映射中,所有未单独指定颜色的图层都会继承该配色规则,geom_signif没有匹配到对应分组时就会默认取Hours第一个因子水平对应的颜色。


解决方法

方法1:统一将显著性条设置为黑色

直接在geom_signif中手动指定colour = "black"覆盖全局映射即可,修改后代码如下:

ggplot(data = data, mapping = aes(y = Fluorescence, x = Treatment, colour = Hours)) + 
  geom_boxplot(outlier.shape = NA) + 
  geom_jitter(position = position_jitterdodge(jitter.width = 0.3, jitter.height = 0), alpha = 0.4) +
  theme(axis.text.x = element_text(angle = 60, hjust = 1)) + 
  xlab("Treatment") +
  ylab("Mean fluorescence") +
  ggtitle("C6/36") +
  geom_signif(y_position = c(5.8,6.3,2.5,2,1.5,0.5,1), 
              xmin = c(2,3,2,2.8,1.8,1.8,2.8),
              xmax = c(3,4,4,10,3.8,2.8,3.8),
              annotations = c("****","****","ns","****","****","ns","**"),
              textsize=3.5,
              colour = "black") # 新增此行覆盖全局颜色

方法2:显著性条颜色匹配对应孵育时间

你可以先整理每个显著性条对应的Hours值,构造和注释长度一致的向量,在geom_signif中单独映射颜色,就会自动沿用全局的Hours配色规则。如果不需要显著性条的映射出现在图例中,可以加show.legend = FALSE参数,示例代码如下:

# 替换为每个显著性条实际对应的Hours值
sig_hours <- c("24h", "24h", "48h", "48h", "72h", "72h", "72h")

ggplot(data = data, mapping = aes(y = Fluorescence, x = Treatment, colour = Hours)) + 
  geom_boxplot(outlier.shape = NA) + 
  geom_jitter(position = position_jitterdodge(jitter.width = 0.3, jitter.height = 0), alpha = 0.4) +
  theme(axis.text.x = element_text(angle = 60, hjust = 1)) + 
  xlab("Treatment") +
  ylab("Mean fluorescence") +
  ggtitle("C6/36") +
  geom_signif(mapping = aes(colour = sig_hours), # 新增颜色映射
              y_position = c(5.8,6.3,2.5,2,1.5,0.5,1), 
              xmin = c(2,3,2,2.8,1.8,1.8,2.8),
              xmax = c(3,4,4,10,3.8,2.8,3.8),
              annotations = c("****","****","ns","****","****","ns","**"),
              textsize=3.5,
              show.legend = FALSE) # 不需要在图例展示时添加此行

你提供的原图参考:
绘图效果示例图


内容的提问来源于stack exchange,提问作者Ellen Masters

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 05:21:03