BioF3 FigCode · SCI 绘图代码集
样本量-功效曲线(Power Curve)
分类:分布可视化 | 依赖包:pwr、ggplot2、tidyr
解决的生物学问题
我要检测 1.5 倍差异需要多少样本?现有样本量能达到 80% power 吗?
应用场景
- Grant 申请样本量论证
- Pilot study 后扩样决策
- 基金课题方案设计
- 审稿人质疑样本量时的回应
输入数据格式
参数:effect_size 范围、显著性水平 α、检验类型
关键参数
- effect_size = c(0.2, 0.5, 0.8)(Cohen d 小/中/大)
- sig.level = 0.05
- type = "two.sample" / "paired"
快速开始
1. 直接在线运行
打开 FigCode 在线绘图,点击本工具卡片的"在线绘图"按钮即可用内置示例数据出图,零环境配置。
2. 本地复现
下载脚本和示例数据,本地 RStudio 运行:
# 下载
curl -O https://<your-site>/figcode/scripts/power-curve.R
curl -O https://<your-site>/figcode/data/power-curve.csv
3. 安装依赖
# CRAN 包
install.packages(c("pwr", "ggplot2", "tidyr"))
# Bioconductor 包(如需)
# BiocManager::install(c())
完整代码
library(pwr)
library(ggplot2)
library(tidyr)
# --- Compute power across n for several effect sizes ---
n_seq <- seq(5, 200, by = 5)
effects <- c(0.2, 0.5, 0.8) # Cohen's d: small / medium / large
df <- expand.grid(n = n_seq, d = effects)
df$power <- mapply(
function(n, d) pwr.t.test(n = n, d = d, sig.level = 0.05,
type = "two.sample")$power,
df$n, df$d
)
df$d_label <- factor(
paste0("d = ", df$d),
levels = paste0("d = ", effects)
)
# --- Plot ---
ggplot(df, aes(n, power, color = d_label)) +
geom_line(size = 1.1) +
geom_hline(yintercept = 0.8, linetype = "dashed", color = "grey50") +
annotate("text", x = max(n_seq), y = 0.81,
label = "Power = 0.80", hjust = 1, size = 3.5, color = "grey40") +
scale_color_manual(values = c("#dc2626", "#059669", "#2563eb"),
name = "Effect size") +
scale_y_continuous(limits = c(0, 1), breaks = seq(0, 1, 0.2)) +
labs(title = "Two-sample t-test Power",
x = "Sample size per group", y = "Statistical power") +
theme_classic()
替换为自己的数据
脚本中以 # --- Demo data --- 标注的段落是示例数据生成代码。替换为自己的数据时,保持列名一致即可:
- 输入格式:参数:effect_size 范围、显著性水平 α、检验类型
- 使用
read.csv()/readRDS()读取本地文件
延伸阅读
- 后续将补充配套教程
- 出现 bug?欢迎在 FigCode 页面 点击对应卡片,在评论区留言。