gpt4 book ai didi

r - 使用 plot.matrix 更改轴标记

转载 作者:行者123 更新时间:2023-12-04 12:36:08 25 4
gpt4 key购买 nike

我有一个矩阵,我想使用 plot.matrix 包将其绘制为 R 中的热图。我的矩阵是 80 x 80,但我只想在每第五行和每列中绘制条目(因此是 16 x 16 非连续子矩阵)。但是,我仍然希望 x 和 y 轴标记为 5、10、15 等,而不是我无法弄清楚的 1、2、3 等。下面是我的代码(矩阵称为 MSE):

byfive = seq(from = 5, to = 80, by = 5)
par(mar=c(5.1, 4.1, 4.1, 4.1))
plot(MSE[byfive, byfive], xlab = "m2", ylab = "m1", main = "Mean-squared error")


这是输出:

enter image description here

我希望轴标记为 5、10、15 等,而不是 1、2、3 等。如果有人知道如何解决这个问题,或者如果有人知道另一个可以轻松做到这一点的软件包,我会非常乐意欣赏它。

最佳答案

由于您是新手,最好包含一个可重现的数据示例,这样我们更容易回答。

要完成它,您只需添加 byfive作为矩阵的行和列名称。


# Vector 80 * 80
mse <- runif(80 * 80, min = 10, max = 14)
# dimentions to matrix
dim(mse) <- c(80, 80)

# index to plot
byfive = seq(from = 5, to = 80, by = 5)

# New matrix keeping elements to plot
mse2 <- mse[byfive, byfive]

# adding row and col names
colnames(mse2) <- byfive
rownames(mse2) <- byfive

# plot
plot(mse2, xlab = "m2", ylab = "m1", main = "Mean-squared error")


enter image description here

使用 tidyverse:

library(ggplot2)
library(dplyr)
library(tidyr)
library(forcats)

mse2 %>%
as.data.frame() %>%
rownames_to_column(var = "m1") %>%
tidyr::pivot_longer(
cols = -m1,
names_to = "m2",
values_to = "mse"
) %>%
ggplot(aes(x = fct_inorder(m2), y = fct_inorder(m1), fill = mse)) +
geom_tile() +
theme_minimal() +
scale_fill_viridis_c() +
labs(x = "m2", y = "m1",
title = "Mean-squared error") +
theme(legend.position = "bottom",
axis.ticks = element_line(color = 'black'))

enter image description here

关于r - 使用 plot.matrix 更改轴标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61570115/

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