2016-06-18 14 views
6

Ho due matrici di confusione con valori calcolati come vero positivo (tp), falsi positivi (fp), veri negativi (tn) e falsi negativi (fn), corrispondenti a due metodi diversi. Voglio rappresentarli come enter image description hereStampare la matrice di confusione in R utilizzando ggplot

Credo che la griglia di sfaccettatura o la sfaccettatura facciale possano farlo, ma trovo difficile iniziare. Ecco i dati di due matrici confusione corrispondenti a Method1 e method2

dframe<-structure(list(label = structure(c(4L, 2L, 1L, 3L, 4L, 2L, 1L, 
3L), .Label = c("fn", "fp", "tn", "tp"), class = "factor"), value = c(9, 
0, 3, 1716, 6, 3, 6, 1713), method = structure(c(1L, 1L, 1L, 
1L, 2L, 2L, 2L, 2L), .Label = c("method1", "method2"), class = "factor")), .Names = c("label", 
"value", "method"), row.names = c(NA, -8L), class = "data.frame") 

risposta

9

Questo potrebbe essere un buon inizio

library(ggplot2) 
ggplot(data = dframe, mapping = aes(x = label, y = method)) + 
    geom_tile(aes(fill = value), colour = "white") + 
    geom_text(aes(label = sprintf("%1.0f",value)), vjust = 1) + 
    scale_fill_gradient(low = "white", high = "steelblue") 

Modificato

TClass <- factor(c(0, 0, 1, 1)) 
PClass <- factor(c(0, 1, 0, 1)) 
Y  <- c(2816, 248, 34, 235) 
df <- data.frame(TClass, PClass, Y) 

library(ggplot2) 
ggplot(data = df, mapping = aes(x = TClass, y = PClass)) + 
    geom_tile(aes(fill = Y), colour = "white") + 
    geom_text(aes(label = sprintf("%1.0f", Y)), vjust = 1) + 
    scale_fill_gradient(low = "blue", high = "red") + 
    theme_bw() + theme(legend.position = "none") 

enter image description here

0

A una soluzione leggermente più modulare basata sulla risposta di MYaseen208. Potrebbe essere più efficace per dataset di grandi dimensioni/classificazione multinomiale:

confusion_matrix <- as.data.frame(table(predicted_class, actual_class)) 

ggplot(data = confusion_matrix 
     mapping = aes(x = predicted_class, 
        y = Var2)) + 
    geom_tile(aes(fill = Freq)) + 
    geom_text(aes(label = sprintf("%1.0f", Freq)), vjust = 1) + 
    scale_fill_gradient(low = "blue", 
         high = "red", 
         trans = "log") # if your results aren't quite as clear as the above example 
Problemi correlati