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

如何自定义stat_pvalue_manual显著性对比线的颜色?

问题描述

需要按规则自定义显著性对比线的颜色:

  • 不同剂量间VC组的对比线设为黄色(#E69F00)
  • 不同剂量间OJ组的对比线设为灰色(#999999)
  • 同剂量下VC与OJ的对比线保持黑色

当前使用stat_pvalue_manual(color = 'supp')可实现分组着色,但需替换为自定义配色方案。

解决方案

给剂量间对比的p值数据框添加自定义颜色列,在stat_pvalue_manual中指定该列作为颜色映射;同剂量对比的线条直接设置为黑色即可。

修改后的完整代码
# 示例数据
plot_df <- ToothGrowth

# 数据汇总
summary_df <- plot_df %>%
  group_by(dose, supp) %>%
  summarise(
    Mean = mean(len),
    SD = sd(len),
    SE = sd(len) / sqrt(n())  # 标准误
  )

# 不同剂量间的组内p值计算
p_sup <- plot_df %>%
  group_by(supp) %>%
  t_test(len ~ dose, p.adjust.method = "fdr") %>%
  add_xy_position(x = "dose", group = "supp") %>%
  # 添加自定义颜色列:VC对应黄色,OJ对应灰色
  mutate(line_color = case_when(
    supp == "VC" ~ "#E69F00",
    supp == "OJ" ~ "#999999"
  ))

# 同剂量下不同组的p值计算
p_dose <- plot_df %>%
  group_by(dose) %>%
  t_test(len ~ supp) %>%
  adjust_pvalue(method = "fdr") %>%
  add_significance("p.adj") %>%
  add_xy_position(x = "dose")

# 将dose转为字符型
summary_df$dose <- as.character(summary_df$dose)

ggplot(summary_df, aes(x = dose, y = Mean, fill = supp)) +
  geom_bar(stat = "identity", color = "black", position = position_dodge()) +
  geom_errorbar(aes(ymin = Mean - SE, ymax = Mean + SE), width = 0.2, position = position_dodge(.9)) +
  theme_minimal() +
  scale_fill_manual(values=c('#999999','#E69F00')) +
  labs(title = 'ToothGrowth',
       x = "剂量",
       y = "长度 ± 标准误")+
  theme(
    plot.title = element_text(hjust = 0.5)
  )+
  # 剂量间对比线使用自定义颜色
  stat_pvalue_manual(
    p_sup,
    tip.length = 0.01, 
    hide.ns = TRUE,
    color = "line_color"  # 指定使用自定义颜色列
  )+
  # 同剂量对比线设为黑色
  stat_pvalue_manual(
    p_dose, tip.length = 0.01,
    hide.ns = TRUE,
    inherit.aes = FALSE,
    color = "black"
  )
效果示例

自定义颜色的显著性对比线示例图

内容的提问来源于stack exchange,提问作者Munkhtur Otgonbayar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 13:09:57