gpt4 book ai didi

r - 如何使用 R 中的热图绘制混淆矩阵?

转载 作者:行者123 更新时间:2023-12-04 11:45:32 26 4
gpt4 key购买 nike

我有一个混淆矩阵,这样:

  a b c d e f g h i j
a 5 4 0 0 0 0 0 0 0 0
b 0 0 0 0 0 0 0 0 0 0
c 0 0 4 0 0 0 0 0 0 0
d 0 0 0 0 0 0 0 0 0 0
e 2 0 0 0 2 0 0 0 0 0
f 1 0 0 0 0 2 0 0 0 0
g 0 0 0 0 0 0 0 0 0 0
h 0 0 0 0 0 0 0 0 0 0
i 0 0 0 0 0 0 0 0 0 0
j 0 0 0 0 0 0 0 0 0 0

其中字母表示类标签。

我只需要绘制混淆矩阵。我搜索了几个工具。 R 中的热图看起来像我需要的。由于我对 R 一无所知,因此很难对样本进行更改。如果有人能很快帮助我如何画画,我将不胜感激。或者也欢迎任何其他建议而不是热图。
我知道有很多关于此的样本,但我仍然无法使用自己的数据进行绘制。

最佳答案

您可以使用 ggplot2 获得不错的结果。 ,但为此您需要一个包含 3 列 x、y 和要绘制的值的 data.frame。

使用 gather来自 tidyr工具很容易重新格式化您的数据:

library("dplyr")
library("tidyr")

# Loading your example. Row names should get their own column (here `y`).
hm <- readr::read_delim("y a b c d e f g h i j
a 5 4 0 0 0 0 0 0 0 0
b 0 0 0 0 0 0 0 0 0 0
c 0 0 4 0 0 0 0 0 0 0
d 0 0 0 0 0 0 0 0 0 0
e 2 0 0 0 2 0 0 0 0 0
f 1 0 0 0 0 2 0 0 0 0
g 0 0 0 0 0 0 0 0 0 0
h 0 0 0 0 0 0 0 0 0 0
i 0 0 0 0 0 0 0 0 0 0
j 0 0 0 0 0 0 0 0 0 0", delim=" ")

# Gathering columns a to j
hm <- hm %>% gather(x, value, a:j)

# hm now looks like:
# # A tibble: 100 x 3
# y x value
# <chr> <chr> <dbl>
# 1 a a 5
# 2 b a 0
# 3 c a 0
# 4 d a 0
# 5 e a 2
# # ... with 95 more rows

完美的!让我们开始绘图。 ggplot2 热图的基本几何图形是 geom_tile我们将提供美学 x , yfill .
library("ggplot2")
ggplot(hm, aes(x=x, y=y, fill=value)) + geom_tile()

First attempt at a heatmap

还不错,但我们可以做得更好。首先,我们可能想要反转 y 轴。诀窍是将 x 和 y 作为因子提供我们想要的级别。
hm <- hm %>%
mutate(x = factor(x), # alphabetical order by default
y = factor(y, levels = rev(unique(y)))) # force reverse alphabetical order

然后我喜欢黑白主题 theme_bw()这摆脱了灰色背景。我也喜欢使用来自 RColorBrewer 的调色板(使用 direction = 1 以获得更高值的更深颜色)。

由于您在 x 上绘制了相同的图和 y轴,您可能想要相等的轴比例: coord_equal()会给你一个正方形的情节。
ggplot(hm, aes(x=x, y=y, fill=value)) +
geom_tile() + theme_bw() + coord_equal() +
scale_fill_distiller(palette="Greens", direction=1)
# Other valid palettes: Reds, Blues, Spectral, RdYlBu (red-yellow-blue), ...

A better heatmap

画龙点睛:在瓷砖顶部打印值并删除图例,因为它不再有用。显然,这都是可选的,但它为您提供了构建 Material 。备注 geom_text继承了 xy美学,因为它们被传递给 ggplot .
ggplot(hm, aes(x=x, y=y, fill=value)) +
geom_tile() + theme_bw() + coord_equal() +
scale_fill_distiller(palette="Greens", direction=1) +
guides(fill=F) + # removing legend for `fill`
labs(title = "Value distribution") + # using a title instead
geom_text(aes(label=value), color="black") # printing values

Final heatmap

您也可以通过 color="black"geom_tile在瓷砖周围绘制(黑色)线。与 RdYlBu 的最终情节配色方案(有关可用调色板的列表,请参阅 RColorBrewer::display.brewer.all())。

Showcasing more options

关于r - 如何使用 R 中的热图绘制混淆矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7421503/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com