Skip to content

Instantly share code, notes, and snippets.

@charly06
Forked from jwaage/ggroc.R
Last active March 20, 2023 15:54
Show Gist options
  • Save charly06/91578196fc615c5a79c7174318be4349 to your computer and use it in GitHub Desktop.
Save charly06/91578196fc615c5a79c7174318be4349 to your computer and use it in GitHub Desktop.
Multiple ROC curves using ggplot2 and pROC
#' Functions plots multiple 'roc' objects into one plot
#' @param rocs
#' A list of 'roc' objects. Every list item has a name.
#' @param breaks
#' A vector of integers representing ticks on the x- and y-axis
#' @param legentTitel
#' A string which is used as legend titel
ggrocs <- function(rocs, breaks = seq(0,1,0.1), legendTitel = "Legend") {
if (length(rocs) == 0) {
stop("No ROC objects available in param rocs.")
} else {
require(plyr)
# Store all sensitivities and specifivities in a data frame
# which an be used in ggplot
RocVals <- plyr::ldply(names(rocs), function(rocName) {
if(class(rocs[[rocName]]) != "roc") {
stop("Please provide roc object from pROC package")
}
data.frame(
fpr = rev(rocs[[rocName]]$specificities),
tpr = rev(rocs[[rocName]]$sensitivities),
names = rep(rocName, length(rocs[[rocName]]$sensitivities)),
stringAsFactors = T
)
})
aucAvg <- mean(sapply(rocs, "[[", "auc"))
rocPlot <- ggplot(RocVals, aes(x = fpr, y = tpr, colour = names)) +
geom_segment(aes(x = 0, y = 1, xend = 1,yend = 0), alpha = 0.5, colour = "gray") +
geom_step() +
scale_x_reverse(name = "False Positive Rate (1 - Specificity)",limits = c(1,0), breaks = breaks) +
scale_y_continuous(name = "True Positive Rate (Sensitivity)", limits = c(0,1), breaks = breaks) +
theme_bw() +
coord_equal() +
annotate("text", x = 0.1, y = 0.1, vjust = 0, label = paste("AUC =",sprintf("%.3f",aucAvg))) +
guides(colour = guide_legend(legendTitel)) +
theme(axis.ticks = element_line(color = "grey80"))
rocPlot
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment