我正在尝试,给定一个n * p数字矩阵,绘制一个带有n * p个正方形的图形,每个正方形的颜色取决于矩阵中的数字。
矩阵定义如下:
ll <- list(c(1,3,4,3,6,5,8),c(1,1,4,5,7,6,8),c(1,3,1,1,3,4,8),c(2,1,1,2,1,3,5))
mm <- do.call(rbind,ll)
以一般方式,我想为一组数字定义颜色。 例如:
然后&#34;情节&#34;矩阵。就像这个链接上的colorfull matplotlib图片一样: http://activeintelligence.org/blog/archive/matplotlib-sparse-matrix-plot/
我真的不知道怎么做,任何观点都会非常感激!
答案 0 :(得分:2)
cc <- mm # make copy to modify
cc[] <- findInterval(cc, c(0, 2.5, 5.5, 8.5 ) ) # values 1:3
cc
image(seq(dim(cc)[1]), seq(dim(cc)[2]), cc, col=c("yellow","orange","red"))
cc -matrix中的值将从颜色矢量中拉出。
答案 1 :(得分:0)
我认为点的位置由n和p等级定义。您可以使用ggplot2和reshape2处理此问题。
ll <- list(c(1,3,4,3,6,5,8),c(1,1,4,5,7,6,8),c(1,3,1,1,3,4,8),c(2,1,1,2,1,3,5))
mm <- do.call(rbind,ll)
rownames(mm) = 1:nrow(mm)
colnames(mm) = 1:ncol(mm)
library(reshape2)
library(ggplot2)
mm_long = melt(mm)
colnames(mm_long) = c("x", "y", "group")
mm_long$colour_group = NA
mm_long$colour_group[mm_long$group %in% c(1,2)] = 1
mm_long$colour_group[mm_long$group %in% c(3,4,5)] = 2
mm_long$colour_group[mm_long$group %in% c(6,7,8)] = 3
mm_long$group = factor(mm_long$group)
mm_long$colour_group = factor(mm_long$colour_group)
ggplot(mm_long, aes(x=x, y=y)) +
geom_point(aes(colour=colour_group), shape=15, size=10) +
scale_colour_manual(values = c("yellow","orange", "red"))
答案 2 :(得分:0)
基本上遵循@MrFlick&amp; @BondedDust:
cols=c(rep("yellow", 2), rep("orange", 3), rep("red", 3))
image(1:ncol(mm), 1:nrow(mm), t(mm), col=cols, breaks=c(0:length(cols))+0.5, xlab="", ylab="")
或
heatmap(mm, col=cols, breaks=c(0:length(cols))+0.5, Colv=NA, Rowv=NA, scale="none")