在R中按颜色创建矩阵 [英] Creating a matrix by color in R
本文介绍了在R中按颜色创建矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我创建了一个测试矩阵4 * 4矩阵:
Say I have created a test matrix 4*4 matrix:
varieties = c("A", "B", "C", "D")
matVar = matrix(c(1,5,3,4,8,5,2,8,9,4,6,5,3,7,3,2), nrow = length(varieties), ncol = length(varieties))
我有一个矩阵看起来如下:
I have a matrix that looks as follows:
[,1] [,2] [,3] [,4]
[1,] 1 8 9 3
[2,] 5 5 4 7
[3,] 3 2 6 3
[4,] 4 8 5 2
如何在R中创建热图图像,以便将行和列命名为变量(A,B,C,D),并且颜色按品种组合之间的价值评分?
How can I create a heatmap image in R such that the rows and columns are named the varieties (A, B, C, D), and the color is graded by the value between that combination of varieties?
我尝试了以下内容:
library(reshape2)
library(ggplot2)
tdm <- melt(matVar)
ggplot(tdm, aes(x = varieties, y = varieties, fill = factor(value))) +
labs(x = "Variety", y = "Variety", fill = "Value") +
geom_raster()
并收到错误:
Error: Aesthetics must either be length one, or the same length as the dataProblems:varieties, varieties
任何建议表示赞赏!
推荐答案
这样的事情?
library(reshape2)
library(ggplot2)
df <- data.frame(id=varieties,matVar)
colnames(df)[2:ncol(df)] <- varieties
gg <- melt(df, id="id")
ggplot(gg, aes(x=id,y=variable,fill=value))+
geom_tile()+
scale_fill_gradient(low="#FFFF88",high="#FF0000")+
coord_fixed()
注意:
-
coord_fixed()
是使用,因此瓷砖是方形的。 -
scale_fill_gradient(...)
用于将填充颜色设置为黄色 - 红色。查看scale_fill_gradientn(...)
和scale_fill_gradient2(...)
的文档,了解其他选项。
coord_fixed()
is used so the tiles are square.scale_fill_gradient(...)
is used to set the fill colors to yellow - red. Look at the documentation forscale_fill_gradientn(...)
andscale_fill_gradient2(...)
for other options.
这篇关于在R中按颜色创建矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文