如何在ggplot2的precision-recall散点图中添加F1等值曲线
在Precision-Recall图中添加F1等值曲线
要添加F1值0.1到0.9的等值曲线,核心是利用F1分数的公式推导生成曲线数据,再用geom_line绘制(geom_curve仅适用于两点间的单条弯曲线段,不适合生成连续等值线)。
步骤1:生成F1等值线数据
F1分数计算公式为:F1 = 2 * (Precision * Recall) / (Precision + Recall)
变形得到Recall关于Precision的表达式:Recall = (F1 * Precision) / (2*Precision - F1)
基于此生成每个F1值对应的坐标点:
# 生成F1值序列(0.1到0.9,步长0.1) f1_values <- seq(0.1, 0.9, by = 0.1) # 生成每个F1对应的precision-recall数据 f1_lines <- lapply(f1_values, function(f1) { # 生成precision取值范围,避开分母为0的点(precision = f1/2) precision <- seq(0.01, 0.99, length.out = 100) recall <- (f1 * precision) / (2 * precision - f1) # 过滤超出[0,1]范围的recall值 recall <- ifelse(recall > 1 | recall < 0, NA, recall) data.frame(precision = precision, recall = recall, f1 = factor(f1, levels = f1_values)) }) %>% do.call(rbind, .)
步骤2:修改原绘图代码添加等值线
将F1曲线数据加入原ggplot代码,用虚线绘制曲线并添加F1值标注:
library(ggplot2) library(RColorBrewer) library(elementalist) library(dplyr) scaleFUN <- function(x) ifelse(x!=0, sprintf("%.2f", x), 0) ggplot() + # 绘制F1等值线(置于底层) geom_line(data = f1_lines, aes(x = precision, y = recall, group = f1), color = "gray70", linetype = "dashed", linewidth = 0.5) + # 添加F1值标注,取precision=0.9处的位置 geom_text(data = f1_lines %>% filter(precision == max(precision, na.rm = T)), aes(x = precision + 0.02, y = recall, label = paste0("F1=", f1)), color = "gray50", size = 3) + # 绘制原数据点 geom_point(data = precision_recall, mapping=aes(x=precision, y=recall, shape=technology, color=approach, size=type), show.legend=T) + theme_bw() + scale_color_manual(values=brewer.pal(12, "Paired")[c(2,4)]) + scale_shape_manual(values=c(16, 18)) + guides(color=guide_legend(ncol=2, keywidth=1, position="inside", order=1, title.position='top', title.hjust=.5), shape=guide_legend(ncol=2, keywidth=1, position="inside", order=2, title.position='top', title.hjust=.5), size=guide_legend(ncol=2, keywidth=1, position="inside", order=3, title.position='top', title.hjust=.5)) + theme(legend.box.background=element_rect_round(color="black", fill="white", linetype="solid", radius=unit(1,"mm")), legend.background=element_rect(fill="transparent"), legend.position.inside=c(0.175,0.78), legend.box='vertical', aspect.ratio=1, panel.grid=element_blank(), plot.margin=unit(c(.2, .5, .2, .2), "cm"), panel.border = element_rect(colour="black", fill=NA, linewidth=1), legend.title=element_text(face='italic')) + coord_cartesian(xlim=c(0, 1.05), ylim=c(0, 1)) + # 扩展x轴容纳标注 scale_x_continuous(labels=scaleFUN) + scale_y_continuous(labels=scaleFUN)
关键说明
- 优先绘制等值线:确保曲线在数据点下方,不遮挡核心数据
- 过滤无效值:计算Recall时会出现超出[0,1]的情况,用
NA过滤避免不合理线段 - 标注位置调整:扩展x轴范围,让F1标注不会超出绘图区域
内容的提问来源于stack exchange,提问作者Matteo
相关产品推荐
相关产品推荐

