rplotrocaucproc-r-package

Adding text to AUC labels using pROC


I wonder if there is a way to annotate the printed AUCs further on my ROC plots?

Currently, it's not clear which line the AUCs belong to in my plot (below). I would like to add more description so that the text looks like:

Is there a way to do this inside the pROC::roc() function?

enter image description here

Here is a producible example using test data:

library(pROC)

testdata = structure(list(outcome = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L), .Label = c("0", 
"1"), class = "factor"), fi = c(0.0395, 0.0835, 0.03975, -0.079, 
-0.00825000000000001, NA, NA, -0.0125, -0.04175, -0.09375, -0.02275, 
0.01675, 0.03325, -0.0165, 0.0165, 0.0585, -0.04175, NA, -0.004, 
0.05, 0.0165, -0.0335, -0.01225, -0.025, 0.01225, NA, 0.05425, 
0.08125, 0.07925, NA, NA, -0.00625, 0.05, 0.06875, NA, 0.0645, 
NA, -0.00625000000000001, 0.03125, 0.07275, 0.00625, 0.027, 0.0665, 
0.023, 0.046, -0.1875, -0.2, -0.002, -0.10225, 0.0605), fp = c(-2, 
-1, -1, -1, 0, NA, NA, 0, 0, -1, 1, 0, 0, 1, NA, NA, -1, NA, 
0, NA, NA, NA, NA, NA, 0, NA, NA, 1, NA, NA, NA, 1, 1, -1, NA, 
NA, NA, 0, 0, NA, 1, 0, NA, 0, 1, 1, 2, 0, 0, -1)), class = "data.frame", row.names = c(NA, 
-50L))


par(pty="s") # change the graphical parameter pty to s before calling plot.roc so that the margins are outside the plot
plot(roc(testdata[["outcome"]], testdata[["fi"]]), print.auc=TRUE, col="black", lty=1, lwd=2, legacy.axes = TRUE, print.auc.y=.35, grid=TRUE)
plot(roc(testdata[["outcome"]], testdata[["fp"]]), print.auc=TRUE, col="black", lty=3, lwd=2, legacy.axes = TRUE, print.auc.y=.3, grid=TRUE, add=TRUE)
legend("bottomright",
       legend=c("Frailty Index", "Frailty Phenotype"),
       col=c("black", "black"),
       lty=c(1,3),
       lwd=c(2,2))
myroc = recordPlot() # saves current plot

Solution

  • You can set print.auc=FALSE and then add the text using text:

    roc_fi <- roc(testdata[["outcome"]], testdata[["fi"]])
    roc_fp <- roc(testdata[["outcome"]], testdata[["fp"]])
    
    plot(roc_fi, print.auc=FALSE, col="black", lty=1, lwd=2, legacy.axes = TRUE, print.auc.y=.35, grid=TRUE)
    plot(roc_fp, print.auc=FALSE, col="black", lty=3, lwd=2, legacy.axes = TRUE, print.auc.y=.3, grid=TRUE, add=TRUE)
    legend("bottomright",
           legend=c("Frailty Index", "Frailty Phenotype"),
           col=c("black", "black"),
           lty=c(1,3),
           lwd=c(2,2))
    
    text(0.4, 0.4, paste("AUC for FI:", round(roc_fi$auc, 3)))
    text(0.4, 0.35, paste("AUC for FP:", round(roc_fp$auc, 3)))