首页 > 解决方案 > 在 r 中绘制一个显示百分比的混淆矩阵(ggplot)

问题描述

所以我有这两列我想变成一个混淆矩阵

faceEmotion
neutral
sad
happy
disgusted
angry
fearful
neutral
sad
sad
happy
happy
fearful

faceEmotionGuess
neutral
sad
happy
disgusted
angry
fearful
sad
disgusted
happy
happy
sad
neutral

我看到了这个用 ggplot 制作的漂亮的混淆矩阵,但我不知道他是如何制作的。谷歌并没有太大帮助。

感谢您提供的任何帮助!

标签: rggplot2confusion-matrix

解决方案


您的示例数据显然不如创建所需图像的示例数据丰富,但您可以从您的数据中创建类似的图,如下所示:

library(ggplot2)

tab <- table(df$faceEmotion, df$faceEmotionGuess)
tab <- tab / rowSums(tab)
tab <- as.data.frame(tab, stringsAsFactors = TRUE)
tab$Var2 <- factor(tab$Var2, rev(levels(tab$Var2)))

ggplot(tab, aes(Var1, Var2, fill = Freq)) +
  geom_tile() +
  geom_text(aes(label = scales::percent(Freq))) +
  scale_fill_gradient(low = "white", high = "#3575b5") +
  labs(x = "Emotion", y = "Guess", title = "Confusion matrix of emotions",
       fill = "Select") +
  theme(plot.title = element_text(size = 25, hjust = 0.5, 
                                  margin = margin(20, 0, 20, 0)),
        legend.title = element_text(size = 14, margin = margin(0, 20, 10, 0)),
        axis.title.x = element_text(margin = margin(20, 20, 20, 20), size = 18),
        axis.title.y = element_text(margin = margin(0, 20, 0, 10), size = 18))

在此处输入图像描述


数据

df <- structure(list(faceEmotion = structure(c(5L, 6L, 4L, 2L, 1L, 
3L, 5L, 6L, 6L, 4L, 4L, 3L), .Label = c("angry", "disgusted", 
"fearful", "happy", "neutral", "sad"), class = "factor"), 
faceEmotionGuess = structure(c(5L, 
6L, 4L, 2L, 1L, 3L, 6L, 2L, 4L, 4L, 6L, 5L), .Label = c("angry", 
"disgusted", "fearful", "happy", "neutral", "sad"), class = "factor")), 
class = "data.frame", row.names = c(NA, -12L))

df
#>    faceEmotion faceEmotionGuess
#> 1      neutral          neutral
#> 2          sad              sad
#> 3        happy            happy
#> 4    disgusted        disgusted
#> 5        angry            angry
#> 6      fearful          fearful
#> 7      neutral              sad
#> 8          sad        disgusted
#> 9          sad            happy
#> 10       happy            happy
#> 11       happy              sad
#> 12     fearful          neutral

reprex 包(v0.3.0)于 2020 年 12 月 11 日创建


推荐阅读