使用ggplot在R中绘制混淆矩阵

问题描述 投票:8回答:2

我有两个混淆矩阵,计算值为真阳性(tp),假阳性(fp),真阴性(tn)和假阴性(fn),对应两种不同的方法。我想把它们表示为enter image description here

我相信facet grid或facet wrap可以做到这一点,但我发现很难开始。这是与method1和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")
r ggplot2 confusion-matrix
2个回答
13
投票

这可能是一个好的开始

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

编辑

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


4
投票

基于MYaseen208答案的模块化解决方案。对于大型数据集/多项分类可能更有效:

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
© www.soinside.com 2019 - 2024. All rights reserved.