在 r 中绘制一个显示百分比的混淆矩阵(ggplot)

Plot a confusion matrix in r showing percentages (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

我看到这个 beautiful confusion matrix 是用 ggplot 制作的,但我不知道他是如何制作的。 Google 帮助不大。

感谢您提供的任何帮助!

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

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 package (v0.3.0)

于 2020-12-11 创建