我有以下(示例)数据,我想绘制它们:
matrix(c("Variable1",0.4,0.5,"string1","Variable2",0.3,
"string2","string3","Variable3"),ncol=3)
我想用数字 0.4,0.5,0.3
创建热图矩阵并使用下三角:
numeric<- matrix(c(1,0.4,0.5,0.4,1,0.3,0.5,0.3,1),ncol=3)
require(graphics)
require(grDevices)
library(colorRamps)
library(lattice)
x <- seq(pi/4, 5*pi, length.out=10)
y <- seq(pi/4, 5*pi, length.out=10)
grid <- expand.grid(X=x, Y=y)
myPanel <- function(x, y, z, ...) {
panel.levelplot(x,y,z,...)
panel.text(x, y, round(z,2),cex=0.578,...)}
levelplot(numeric,panel=myPanel)
在包括热图对角线的上三角形上,我想要有字符,其值 "string1", "string2", "string3", "Variable1", "Variable2", "Variable3"
在与给定矩阵相同的网格位置上!
我想到以某种方式创建一个网格并使用 image()
图形包的功能可以为数字着色,但这对我不起作用。
你有一个简单而优雅的函数,只需要给定的矩阵作为输入吗?
最佳答案
您可以尝试ComplexHeatmap您可以通过它自定义热图主体的包:
首先创建一个对称矩阵:
set.seed(123)
mat = matrix(rnorm(100), 10)
colnames(mat) = letters[1:10]
mat2 = cor(mat)
对行和列进行聚类并调整顺序:
od = hclust(dist(mat2))$order
mat2 = mat2[od, od]
现在我们可以自定义热图了。在以下代码中,col
控制如何将值映射到颜色。
由于已经应用了聚类,因此我们将 cluster_rows
和 cluster_columns
设置为 FALSE
。
当 gpar()
中的 type
设置为 none
时,热图会被初始化,但不会添加任何内容,
然后我们可以使用自定义函数cell_fun
向其中添加图形。
cell_fun
将应用于热图中的每个小网格。
在 cell_fun
中,有七个参数:
j
:mat2
中的列索引i
:mat2
中的行索引x
:绘图上的位置y
:绘图上的位置w
:当前网格的宽度h
:当前网格的高度col
:当前网格的填充颜色
使用Heatmap()
生成最终的热图:
Heatmap(mat2, col = colorRamp2(c(-1, 0, 1), c("green", "white", "red")),
cluster_rows = FALSE, cluster_columns = FALSE,
heatmap_legend_title = "cor", rect_gp = gpar(type = "none"),
cell_fun = function(j, i, x, y, w, h, col) {
if(i > j) {
grid.rect(x, y, w, h, gp = gpar(fill = col))
} else if(j == i) {
grid.text(labels[i], x, y)
} else {
grid.text(sprintf("%.2f", mat2[i, j]), x, y)
}
grid.rect(x, y, w, h, gp = gpar(fill = NA, col = "black"))
})
关于r - 创建二次矩阵,其中下三角作为热图,上三角字符数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31625359/