Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot confusion matrix in R using ggplot

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 methods. I want to represent them as enter image description here

I believe facet grid or facet wrap can do this, but I find difficult to start. Here is the data of two confusion matrices corresponding to method1 and 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")
like image 620
Haroon Rashid Avatar asked Jun 18 '16 13:06

Haroon Rashid


People also ask

How do you plot a confusion matrix?

Plot Confusion Matrix for Binary Classes With Labels You need to create a list of the labels and convert it into an array using the np. asarray() method with shape 2,2 . Then, this array of labels must be passed to the attribute annot . This will plot the confusion matrix with the labels annotation.

What is confusion matrix with example?

Confusion Matrix is a useful machine learning method which allows you to measure Recall, Precision, Accuracy, and AUC-ROC curve. Below given is an example to know the terms True Positive, True Negative, False Negative, and True Negative. True Positive: You projected positive and its turn out to be true.


1 Answers

This could be a good start

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")

Edited

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

like image 147
MYaseen208 Avatar answered Sep 20 '22 11:09

MYaseen208