Plot confusion matrix in R using ggplot

前端 未结 5 2034
情歌与酒
情歌与酒 2020-12-29 08:38

I have two confusion matrices with calculated values as true positive (tp), false positives (fp), true negatives(tn) and false negatives (fn), corresponding to two different

5条回答
  •  被撕碎了的回忆
    2020-12-29 08:56

    Here's another ggplot2 based option; first the data (from caret):

    library(caret)
    
    # data/code from "2 class example" example courtesy of ?caret::confusionMatrix
    
    lvs <- c("normal", "abnormal")
    truth <- factor(rep(lvs, times = c(86, 258)),
                    levels = rev(lvs))
    pred <- factor(
      c(
        rep(lvs, times = c(54, 32)),
        rep(lvs, times = c(27, 231))),
      levels = rev(lvs))
    
    confusionMatrix(pred, truth)
    

    And to construct the plots (substitute your own matrix below as needed when setting up "table"):

    library(ggplot2)
    library(dplyr)
    
    table <- data.frame(confusionMatrix(pred, truth)$table)
    
    plotTable <- table %>%
      mutate(goodbad = ifelse(table$Prediction == table$Reference, "good", "bad")) %>%
      group_by(Reference) %>%
      mutate(prop = Freq/sum(Freq))
    
    # fill alpha relative to sensitivity/specificity by proportional outcomes within reference groups (see dplyr code above as well as original confusion matrix for comparison)
    ggplot(data = plotTable, mapping = aes(x = Reference, y = Prediction, fill = goodbad, alpha = prop)) +
      geom_tile() +
      geom_text(aes(label = Freq), vjust = .5, fontface  = "bold", alpha = 1) +
      scale_fill_manual(values = c(good = "green", bad = "red")) +
      theme_bw() +
      xlim(rev(levels(table$Reference)))
    

    option 1

    # note: for simple alpha shading by frequency across the table at large, simply use "alpha = Freq" in place of "alpha = prop" when setting up the ggplot call above, e.g.,
    ggplot(data = plotTable, mapping = aes(x = Reference, y = Prediction, fill = goodbad, alpha = Freq)) +
      geom_tile() +
      geom_text(aes(label = Freq), vjust = .5, fontface  = "bold", alpha = 1) +
      scale_fill_manual(values = c(good = "green", bad = "red")) +
      theme_bw() +
      xlim(rev(levels(table$Reference)))
    

    option 2

提交回复
热议问题