R/3_ROC_plot_example.R

Defines functions plot_roc

Documented in plot_roc

#' [.] Plot ROC - sample code
#'
#' @param roc ...
#' @param threshold ...
#' @param cost_of_fp ...
#' @param cost_of_fn ...
#'
#' @return ...
#' @source \url{https://github.com/joyofdata/joyofdata-articles/blob/master/roc-auc/plot_roc.R}
#'
#' @examples
#' ...
#' @export

plot_roc <- function(roc, threshold, cost_of_fp, cost_of_fn) {
    library(gridExtra)

    norm_vec <- function(v) (v - min(v))/diff(range(v))

    idx_threshold = which.min(abs(roc$threshold-threshold))

    col_ramp <- colorRampPalette(c("green","orange","red","black"))(100)
    col_by_cost <- col_ramp[ceiling(norm_vec(roc$cost)*99)+1]
    p_roc <- ggplot(roc, aes(fpr,tpr)) +
        geom_line(color=rgb(0,0,1,alpha=0.3)) +
        geom_point(color=col_by_cost, size=4, alpha=0.5) +
        coord_fixed() +
        geom_line(aes(threshold,threshold),
                  color=rgb(0,0,1,alpha=0.5)) +
        labs(title = sprintf("ROC")) +
        xlab("FPR") +
        ylab("TPR") +
        geom_hline(yintercept=roc[idx_threshold,"tpr"],
                   alpha=0.5, linetype="dashed") +
        geom_vline(xintercept=roc[idx_threshold,"fpr"],
                   alpha=0.5, linetype="dashed")

    p_cost <- ggplot(roc, aes(threshold, cost)) +
        geom_line(color=rgb(0,0,1,alpha=0.3)) +
        geom_point(color=col_by_cost, size=4, alpha=0.5) +
        labs(title = sprintf("cost function")) +
        geom_vline(xintercept=threshold, alpha=0.5, linetype="dashed")

    sub_title <- sprintf("threshold at %.2f - cost of FP = %d, cost of FN = %d",
                         threshold, cost_of_fp, cost_of_fn)

    grid.arrange(p_roc, p_cost, ncol=2,
                 sub=textGrob(sub_title,
                              gp=gpar(cex=1), just="bottom"))
}
GegznaV/spHelper documentation built on April 16, 2023, 1:42 p.m.