Ck7
Ck7

Reputation: 45

How to plot confusion matrix in R with caret package

How can I plot a confusion matrix with colour in R? I have the confusion matrix statistic but I have no idea how to plot it into a visualise plot. Anyone please assist. Thanks.

# Training Naive Bayes model using {caret} package with 10 fold cross validation
NBclassifierCaretCV <- train(x=data[, -1], y=data$diagnosis, 'nb',
                             trControl=trainControl(method='cv', number=10))
CVtrainDataset <- predict(NBclassifierCaretCV, newdata=data[, -1])

# Confusion matrix and a summary / using caret package
confusionMatrix(data=CVtrainDataset, data$diagnosis)

Upvotes: 2

Views: 2378

Answers (1)

Sheykhmousa
Sheykhmousa

Reputation: 199

Say you have your confusion matrix as following:

pred <- factor(sample(1:5, 100, replace = T))
ref<- factor(sample(1:5, 100, replace = T))
library(caret)
cm <- confusionMatrix(pred, ref)

Then, you would want to retrieve/create some information such as:

library(ggplot2)     
library(grid)
library(gridExtra)           
library(likert)

cm <- confusionMatrix(pred,ref) #create a confusion matrix
cm_d <- as.data.frame(cm$table) # extract the confusion matrix values as data.frame
cm_st <-data.frame(cm$overall) # confusion matrix statistics as data.frame
cm_st$cm.overall <- round(cm_st$cm.overall,2) # round the values
cm_d$diag <- cm_d$Prediction == cm_d$Reference # Get the Diagonal
cm_d$ndiag <- cm_d$Prediction != cm_d$Reference # Off Diagonal     
cm_d[cm_d == 0] <- NA # Replace 0 with NA for white tiles
cm_d$Reference <-  reverse.levels(cm_d$Reference) # diagonal starts at top left
cm_d$ref_freq <- cm_d$Freq * ifelse(is.na(cm_d$diag),-1,1)

plotting the matrix

plt1 <-  ggplot(data = cm_d, aes(x = Prediction , y =  Reference, fill = Freq))+
  scale_x_discrete(position = "top") +
  geom_tile( data = cm_d,aes(fill = ref_freq)) +
  scale_fill_gradient2(guide = FALSE ,low="red3",high="orchid4", midpoint = 0,na.value = 'white') +
  geom_text(aes(label = Freq), color = 'black', size = 3)+
  theme_bw() +
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        legend.position = "none",
        panel.border = element_blank(),
        plot.background = element_blank(),
        axis.line = element_blank(),
        )

plotting the stats

plt2 <-  tableGrob(cm_st)

all together

grid.arrange(plt1, plt2, nrow = 1, ncol = 2, 
             top=textGrob("Confusion Matrix",gp=gpar(fontsize=25,font=1)))

This is not the most beautiful plot but you can change the graphical component later.

enter image description here

Reference HERE and HERE

Upvotes: 1

Related Questions