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

如何按两组统计显著性差异对ggplot的X轴排序

按组间差异显著性排序ggplot的X轴

核心思路

先计算每个测试项的组间差异显著性指标(如p值),再基于该指标对X轴的测试项重新排序。


步骤1:计算每个测试的组间显著性p值

使用t.test(适合正态分布数据)对每个测试项分别做两党得分的差异检验,批量处理代码如下:

library(dplyr)
library(broom)

# 分组计算每个测试的t检验结果,提取p值
sig_stats <- sample_df %>%
  group_by(Test) %>%
  summarise(test_result = list(t.test(Score ~ Party))) %>%
  mutate(tidy_result = map(test_result, tidy)) %>%
  unnest(tidy_result) %>%
  select(Test, p.value)

步骤2:合并显著性数据并绘制排序后的图表

将p值合并到原数据集,用reorder()函数根据p值排序测试项——p值越大(差异越不显著)越靠左,p值越小(差异越显著)越靠右:

library(ggplot2)

# 合并显著性数据到原数据集
df_combined <- left_join(sample_df, sig_stats, by = "Test")

# 生成排序后的图表
ggplot(df_combined, aes(x = reorder(Test, p.value), y = Score, color = Party)) +
  scale_color_manual(name = "Condition", 
                     values = c("#CB454A", "#2E74C0"), 
                     labels = c("Republican", "Democrat")) +
  geom_point(stat = "summary", fun = "mean") +
  geom_errorbar(stat = "summary", fun.data = "mean_se", fun.args = list(mult = 1.96), width = 0) +
  theme(axis.text.x = element_text(size = rel(0.5), angle = 90))

可选调整

  • 如果数据不满足t检验前提,替换为非参数检验:将代码中的t.test改为wilcox.test即可。
  • 若想按「显著到不显著」排序,只需把reorder(Test, p.value)改为reorder(Test, -p.value)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 13:25:33