加载库并创建可重现的示例
#Load libraries
set.seed(123)
library(tidyr)
library(ggplot2)
#Creating a fake pairwise matrix
locs <- 5
tmp <- matrix(runif(n = locs*locs),nrow = locs,ncol = locs)
tmp[upper.tri(tmp,diag = T)] <- NA
colnames(tmp) <- LETTERS[1:locs]
rownames(tmp) <- LETTERS[1:locs]
tmp
#Converting into a data frame
tmp1 <- as.data.frame(cbind(rownames(tmp),as.data.frame(tmp)))
names(tmp1)[1] <- "locA"
rownames(tmp1) <- NULL
head(tmp1)
#Changing it to long form and getting rid of NAs
tmp1 <- gather(tmp1, key = "locB",value = "value",-locA)
tmp1 <- tmp1[!is.na(tmp1$value),]
tmp1
#Making a tiled plot based on default levels
ggplot(tmp1, aes(x = locA, y=locB, fill=value, label=round(value,3)))+
geom_tile(color="black")+
geom_text(size=5,color="white")
但出于更具生物学意义的原因,我想更改这些比较的排序顺序
#biological order
my.order <- c("A","C","D","B","E")
my.order
#re-leveling
tmp1$locA <- factor(tmp1$locA, levels = my.order,ordered = T)
tmp1$locB <- factor(tmp1$locB, levels = my.order,ordered = T)
tmp1
#the releveled plot
ggplot(tmp1, aes(x = locA, y=locB, fill=value, label=round(value,3)))+
geom_tile(color="black")+
geom_text(size=5,color="white")
我试图找到一种方法来让“BC”和“BD”比较在下对角线中表示。
我试图找到一个具有完整矩阵和 lower.tri() 的解决方案,但到目前为止都失败了
#here is the full matrix
x <- tmp
x[is.na(x)] <- 0
y <- t(tmp)
y[is.na(y)] <- 0
full.matrix <- x+y
full.matrix
#the function lower.tri might be useful in this context
lower.tri(full.matrix)