r - 在 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 制作的漂亮的混淆矩阵,但我不知道他是如何制作的。谷歌并没有太大帮助。
感谢您提供的任何帮助!
解决方案
您的示例数据显然不如创建所需图像的示例数据丰富,但您可以从您的数据中创建类似的图,如下所示:
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 日创建
推荐阅读
- php - 如何在 XAMPP 文件夹之外打开 PHP 文件?
- powershell - Powerhell - WMI 和程序和功能不一定相关,我们如何才能准确了解所有已安装的软件?
- mongodb - Mongoose:聚合获取数组类型字段的文档并根据特定字段过滤这些文档
- google-sheets - 根据其他单元格中的值查找特定单元格的值
- r - 当数字的值中有 2 个或更多点时,如何将列设置为数字?
- android - 找不到 google play android 文档
- c++ - 在代码块中安装 C++ 库
- java - 使用 java 从 hashmap 中获取键并存储在 String 数组中
- transliteration - 什么音译 € -> EU 和 ™ -> (tm)?
- mysql - Sending Blobs from MYSQL to Oracle