绘图矩阵有三种颜色

时间:2013-08-22 17:46:42

标签: r heatmap

我正在尝试绘制数据:

NA B B A  B A NA B A NA
B  B B NA B B A  B A B
.
.
B  B B NA A A B  B A B

for each line
If A = red dot
if B = black dot
if NA = grey dot

有人可以帮助我如何做到这一点

2 个答案:

答案 0 :(得分:3)

你的问题不是很清楚,但也许是这样的?

#some data
set.seed(42)
dat <- matrix(sample(c("A","B",NA), 25, TRUE), 5)
#     [,1] [,2] [,3] [,4] [,5]
# [1,] NA   "B"  "B"  NA   NA  
# [2,] NA   NA   NA   NA   "A" 
# [3,] "A"  "A"  NA   "A"  NA  
# [4,] NA   "B"  "A"  "B"  NA  
# [5,] "B"  NA   "B"  "B"  "A" 

#reshape, so ggplot likes it
library(reshape2)
df <- melt(t(dat))
df$value <- as.character(df$value)

#to be able to plot NA values
df$value[is.na(df$value)] <- "NA"

library(ggplot2)
ggplot(df, aes(x=Var1, y=-Var2, fill=value)) + 
  geom_tile() +
  scale_x_continuous(expand=c(0,0), breaks=seq_len(max(df$Var1))) +
  scale_y_continuous(expand=c(0,0), breaks=-seq_len(max(df$Var2)),
                     labels=seq_len(max(df$Var2))) +
  scale_fill_manual(values=c("A"="red", "B"="black", "NA"="grey")) +
  theme_bw() +
  theme(axis.title=element_blank())

enter image description here

如果您真的更喜欢点,可以使用geom_point

修改

如果你的矩阵有dimnames:

rownames(dat) <- letters[1:5]
colnames(dat) <- letters[6:10]
#    f   g   h   i   j  
# a NA  "B" "B" NA  NA 
# b NA  NA  NA  NA  "A"
# c "A" "A" NA  "A" NA 
# d NA  "B" "A" "B" NA 
# e "B" NA  "B" "B" "A"

#reshape, so ggplot likes it
library(reshape2)
df <- melt(t(dat))
df$value <- as.character(df$value)

#to be able to plot NA values
df$value[is.na(df$value)] <- "NA"

#get the order of rows as in print(dat)
df$Var1 <- factor(as.character(df$Var1), levels=colnames(dat), ordered=TRUE)
df$Var2 <- factor(as.character(df$Var2), levels=rev(rownames(dat)), ordered=TRUE)

library(ggplot2)
ggplot(df, aes(x=Var1, y=Var2, fill=value)) + 
  geom_tile() +
  scale_x_discrete(expand=c(0,0)) +
  scale_y_discrete(expand=c(0,0)) +
  scale_fill_manual(values=c("A"="red", "B"="black", "NA"="grey")) +
  theme_bw() +
  theme(axis.title=element_blank())

enter image description here

答案 1 :(得分:1)

提供此示例只是为了详细说明如何完成它。这远非最紧凑的代码。

dmat[dmat=="A"]<-0
dmat[dmat=="B"]<-1
dmat[is.na(dmat)]<-2
mycolors<-c('red','black','grey')
# initial plot area
plot(c(1,nrow(dmat)),c(1,ncol(dmat)),t='n')

for (i in 1:nrow(dmat)){
   for(j in 1:ncol(dmat)) {
       points(i,j,col=mycolors[dmat[i,j]])
       }
   }