在R中绘制整数矩阵

时间:2013-10-22 13:40:15

标签: r plot ggplot2 heatmap

我有100x100整数矩阵(每个变量代表一个百分比值)。所以我想通过热图绘制数据(我猜这个是合适的)。另外,由于条件的原因,我想让区域明显分开;如果“百分比> 50”则将该区域绘制成红色,相对于“百分比”的值。例如,如果百分比是80,那么它的红色将比50的百分比更深。那么你可以看到我正在尝试做的一个例子。

enter image description here

我会非常感激任何帮助。不管怎样,谢谢

编辑:以下是阅读和构建矩阵的示例代码。

library(ggplot2)

outcomeMatrix <- read.table("probMatrix.txt")

firstCol = as.numeric(outcomeMatrix[1,])
firstRow = as.numeric(outcomeMatrix[,1])

matrix <- as.matrix(scale(outcomeMatrix))

你可以在下面看到一个数据样本(10x10矩阵)

Data

2 个答案:

答案 0 :(得分:2)

此外,image可能会有所帮助:

#matrix with the part of your data 10x10 you uploaded
mat <- as.matrix(read.table(text = "0 0 0 0 0 0 0 0 0 0
41 10 2 0 0 0 0 0 0 0
75 36 20 9 4 2 1 0 0 0
91 65 47 31 20 13 8 5 3 2
97 78 64 47 35 25 18 12 8 5
99 88 76 63 50 39 29 22 16 11
99 93 85 74 63 52 42 32 25 19
99 96 91 83 73 64 53 44 35 28
99 98 94 88 81 72 64 54 46 37
99 98 96 92 87 80 72 64 55 47"))

#neccessary step to `image` the expected. read `?image`
t_mat <- t(mat[ncol(mat):1,])

#basic plot
image(t_mat, col = colorRampPalette(c("blue", "red"))(10), axes = F)

#creaty matrix with `NA`s and fill 
#only the values you want to appear yellow.
#here: say 45 to 55
yellows <- matrix(nrow = nrow(t_mat), ncol = ncol(t_mat))
yellows[which(t_mat > 45 & t_mat < 55)] <- t_mat[which(t_mat > 45 & t_mat < 55)] 

#overlay "yellows" to basic plot
image(yellows, col = rgb(1,1,0,1/2), add = T)

情节看起来:

enter image description here

P.S。我猜这是黄色边框的用途。对不起,如果我误解了。

修改

添加了示例legend和标签:

title(main = "imageplot", xlab = "x axis", ylab = "y axis")
legend(x = 0.6, y = 1.15, legend = c("<45", "45-55", ">55"), 
           fill = c("blue", rgb(1,1,0,1/2), "red"), xpd = T, ncol = 3) 

<强> EDIT2

为两个轴添加了标签:

#I guess you'll need to use `axis(1, at = seq(0,1,0.0101), labels = seq(1, 100, 1))` 
#but I'm not sure
axis(1, at = seq(0,1,0.11), labels = seq(1, 10, 1)) 
axis(2, at = seq(0,1,0.11), labels = seq(1, 10, 1))

答案 1 :(得分:1)

这样的东西?

## Random data
set.seed(1337)
m <- matrix(runif(10000, 0, 100), ncol=100,nrow=100)

## Reshape data to long format
mm <- melt(m)

## Plot
ggplot(data=mm) +
    geom_tile(aes(x=Var1, y=Var2, fill=value)) +
    scale_fill_gradient2(low="blue", mid="white", high="red", midpoint=50)

enter image description here