BioF3 FigCode · SCI 绘图代码集
Precision-Recall 曲线(PR Curve)
分类:生存分析 | 依赖包:PRROC、ggplot2、pROC
解决的生物学问题
阳性样本占比很低(如 5%)时,模型在 precision 和 recall 之间的 tradeoff 如何?
应用场景
- 罕见病诊断(阳性极少)
- 癌症早筛低发病率
- 蛋白互作预测(正例稀疏)
- 不平衡 multi-omics 分类
输入数据格式
数据框:truth (0/1), score (0-1)
关键参数
- recall.thresh(计算 AP 时的 recall 阈值)
- pos_label = 1(阳性类编码)
快速开始
1. 直接在线运行
打开 FigCode 在线绘图,点击本工具卡片的"在线绘图"按钮即可用内置示例数据出图,零环境配置。
2. 本地复现
下载脚本和示例数据,本地 RStudio 运行:
# 下载
curl -O https://<your-site>/figcode/scripts/pr-curve.R
curl -O https://<your-site>/figcode/data/pr-curve.csv
3. 安装依赖
# CRAN 包
install.packages(c("PRROC", "ggplot2", "pROC"))
# Bioconductor 包(如需)
# BiocManager::install(c())
完整代码
library(PRROC)
library(ggplot2)
# --- Demo: imbalanced data (5% positive) ---
set.seed(42)
n <- 1000
truth <- rbinom(n, 1, 0.05)
score <- truth * 0.6 + rnorm(n, 0, 0.4)
# --- PR curve ---
pr <- pr.curve(
scores.class0 = score[truth == 1],
scores.class1 = score[truth == 0],
curve = TRUE
)
# Also compute ROC for reference
library(pROC)
roc_obj <- roc(truth, score)
# --- Plot ---
df_pr <- data.frame(
Recall = pr$curve[, 1],
Precision = pr$curve[, 2]
)
baseline <- mean(truth)
ggplot(df_pr, aes(Recall, Precision)) +
geom_path(color = "#dc2626", size = 1.2) +
geom_hline(yintercept = baseline, linetype = "dashed", color = "grey50") +
annotate("text", x = 0.7, y = 0.85,
label = sprintf("AP = %.3f\nBaseline = %.3f\n(ROC AUC = %.3f)",
pr$auc.integral, baseline, auc(roc_obj)),
hjust = 0, size = 3.6) +
labs(title = "Precision-Recall Curve", x = "Recall", y = "Precision") +
scale_x_continuous(limits = c(0, 1)) +
scale_y_continuous(limits = c(0, 1)) +
theme_classic()
替换为自己的数据
脚本中以 # --- Demo data --- 标注的段落是示例数据生成代码。替换为自己的数据时,保持列名一致即可:
- 输入格式:数据框:truth (0/1), score (0-1)
- 使用
read.csv()/readRDS()读取本地文件
延伸阅读
- 相关教程:Precision-Recall 曲线 完整流程
- 出现 bug?欢迎在 FigCode 页面 点击对应卡片,在评论区留言。