我试图绘制数据图矩阵的样子:三种颜色
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
可能有人帮助我,我怎么能做到这一点
我试图绘制数据图矩阵的样子:三种颜色
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
可能有人帮助我,我怎么能做到这一点
你的问题不是很清楚,但也许像这个?
#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())
如果你真的喜欢小点,你可以使用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())
这个例子只提供了在血淋淋的细节显示它如何做。这远不是最紧凑的代码。
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]])
}
}
我不知道为什么我会得到这个错误:for(i in 1:nrow(dat)){ + for(j in 1:ncol(dat){ 错误:意外'{'in: “for (i in 1:nrow(dat)){对于(j in 1:ncol(dat){ “ 点(I,J,COL = mycolors [DAT [I,J]])}} 错误:意想不到在 '}'” 的点(I,J,COL = mycolors [DAT [I,J]])} “ – EpiMan
@MaryamSani对不起 - 我在”for(j ...“)行中留下了一个括号。现在修复。 –
@SeñorO我库仑不来,但我想是这样的:情节(矩阵,XLIM = C(1,nrow),ylim = C(1,NcoI位),TYPE = “N”)sapply(1 :nrow,function(X){points(1:ncol,rep(X,ncol),pch = ifelse(matrix [1,] ==“NA”,19,1))}) – EpiMan