BioF3 FigCode · SCI 绘图代码集

Precision-Recall 曲线(PR Curve)

导出日期:2026年6月27日

分类:生存分析 | 依赖包:PRROC、ggplot2、pROC

解决的生物学问题

阳性样本占比很低(如 5%)时,模型在 precision 和 recall 之间的 tradeoff 如何?

应用场景

输入数据格式

数据框:truth (0/1), score (0-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 --- 标注的段落是示例数据生成代码。替换为自己的数据时,保持列名一致即可:

延伸阅读