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

如何用ggplot的annotate绘制coin包median_test的统计结果?

提取coin包median_test结果并绘制文本

问题背景

有两组住院时长数据(分组为"Low"和"Normal"),需检验组间中位数差异,并通过ggplot的annotate()函数将检验结果以文本形式绘制。使用基础的t.test()时可直接用$提取统计量和p值,但coin包的median_test()返回S4类对象,使用$会报错:Error in medtest$statistic : $ operator not defined for this S4 class。

解决方案

S4类对象需通过@访问内部槽位,或使用coin包提供的专用提取函数来获取统计量和p值,以下是两种可行方法:

方法1:直接访问S4槽位

# 执行中位数检验
medtest <- median_test(LengthOfStay ~ Group, data)

# 提取统计量和p值
stat_val <- medtest@statistic@teststatistic
p_val <- medtest@pvalue

# 构造文本内容
text_content <- paste(
  "检验统计量: ", round(stat_val, 3), "\n",
  "p值: ", round(p_val, 3),
  sep = ""
)

# 绘制文本
library(ggplot2)
ggplot() +
  annotate("text", x = 0.5, y = 0, size = 4, label = text_content, hjust = 0.5) +
  theme_void()

方法2:使用coin包内置提取函数(更规范)

coin包提供了statistic()和pvalue()函数,专门用于提取检验结果,避免直接操作S4槽位:

# 执行中位数检验
medtest <- median_test(LengthOfStay ~ Group, data)

# 提取统计量和p值
stat_val <- statistic(medtest)
p_val <- pvalue(medtest)

# 构造文本内容
text_content <- paste(
  "检验统计量: ", round(stat_val, 3), "\n",
  "p值: ", round(p_val, 3),
  sep = ""
)

# 绘制文本
library(ggplot2)
ggplot() +
  annotate("text", x = 0.5, y = 0, size = 4, label = text_content, hjust = 0.5) +
  theme_void()

说明

  • 两种方法均可正确提取结果,推荐使用方法2,因为它更符合S4对象的操作规范,且在包版本更新时更稳定。
  • 可通过round()函数对数值进行取整,让文本显示更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 12:33:24