问题描述
我有下面的4x4数字矩阵,其中包含数字0-4:
I have the following 4x4 number matrix containing the numbers 0-4:
0 1 0 3
3 2 1 4
4 1 0 2
3 3 0 1
我想了解如何使用R选择的颜色和特定的正方形尺寸(长x宽)将数字矩阵转换为颜色矩阵.为清楚起见,我将颜色矩阵定义为使用彩色正方形表示的图形矩阵方向的特定值.来自另一个程序的示例4x4如下:
I would like to understand how to convert number matrices into a color matrices using chosen colors and specific square dimensions (length x width) using R. To be clear, I'm defining color matrix as a figure using colored squares to represent specific values in a matrix orientation. An example 4x4 from another program follows:
我必须为数字分配颜色代码,例如:
I would have to assign color codes to the numbers, for example:
0 = FFFFFF
1 = 99FF66
2 = 66FF33
3 = 33CC00
4 = 009900
但是我不知道从哪里开始.我想我也必须为颜色方块指定尺寸.
But I don't know where to begin putting this together. I imagine I would also have to specify dimensions for color squares as well.
我的目标是能够将最多10个数值的数据框导入R,并为最大20x20的矩阵创建这些色表.
My goal is to be able to import a data frame into R with up to 10 numerical values and create these color charts for matrices as large as 20x20.
推荐答案
这就是我要做的:
d<-read.table(text="
0 1 0 3
3 2 1 4
4 1 0 2
3 3 0 1")
cols <- c(
'0' = "#FFFFFF",
'1' = "#99FF66",
'2' = "#66FF33",
'3' = "#33CC00",
'4' = "#009900"
)
# the names aren't necessary here.
image(1:nrow(d), 1:ncol(d), as.matrix(d), col=cols)
如果您希望方向不同,可以旋转矩阵:
If you'd prefer for the orientation to be different, you can rotate the matrix:
image(1:nrow(d), 1:ncol(d), t(apply(d, 2, rev)), col=cols)
要摆脱所有文本和边框,您可以尝试:
To get rid of all the text and borders, you might try:
image(1:nrow(d), 1:ncol(d), as.matrix(d), col=cols,
xaxt="n", yaxt="n", bty="n", xlab="", ylab="")
这篇关于在R中将数字矩阵转换为颜色矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!