image {graphics}
Creates a grid of colored or gray-scale rectangles with colors corresponding to the values in z
. This can be used to display three-dimensional or spatial data aka images. This is a generic function.
image(x, ...) ## Default S3 method: image(x, y, z, zlim, xlim, ylim, col = hcl.colors(12, "YlOrRd", rev = TRUE), add = FALSE, xaxs = "i", yaxs = "i", xlab, ylab, breaks, oldstyle = FALSE, useRaster, ...)
### 样本数据
data <- matrix(abs(rnorm(50,0,0.1)), nrow = 10, ncol = 5, byrow = TRUE)
m <- nrow(data)
n <- ncol(data)
colnames(data) <- paste0('y',1:n)
rownames(data)<- paste0('x',1:m)
### 设定绘图参数
breaks.frequency <- seq(from=min(data), to=max(data),
length.out=m * n)
# myColors <- colorRampPalette(c("red", "blue"))
colPal = "BrBG" # palette name 调色板名称
# display.brewer.all() # 显示所有调色板
# Creates nice looking color palettes especially for thematic maps
col_pal = RColorBrewer::brewer.pal(9, colPal)
# 返回插值一组给定颜色以创建新调色板的函数
myColors = grDevices::colorRampPalette(colors = col_pal)
### 绘制热图
par(fig=c(0,1,0,1))
image(1:nrow(data), 1:ncol(data), data,
breaks=breaks.frequency , # more breakpoint than colour
col=myColors(length(breaks.frequency)-1),
axes = FALSE, cex = 1.5, xlab = "", ylab = "",
xlim = c(0,nrow(data)+6), ylim = c(0,ncol(data)))
# 加分割线
abline(h = 0:ncol(data) + 0.5, col = "white", lwd = 0.5)
abline(v = 0:nrow(data) + 0.5, col = "white", lwd = 0.5)
# 加文字
mtext(side = 2, at = 1:n, text = colnames(data),
cex = 1, font = 3)
mtext(side = 3, at = 1:m, text = rownames(data),
cex = 1, font = 3)
### 格子中绘制符号
pvalue <- c(0.01,0.05)
pvSymbols = c(46, 42)
sigSymbolsSize = 2
w = which(data < min(pvalue), arr.ind = TRUE)
points(w, pch = pvSymbols[2], col = "black", cex = sigSymbolsSize)
w = which(data < max(pvalue) & data > min(pvalue), arr.ind = TRUE)
points(w, pch = pvSymbols[1], col = "black", cex = sigSymbolsSize)
### 符号说明
points(x = m + 2, y = n-1, pch = pvSymbols[2],
cex = sigSymbolsSize)
text(x = m + 2, y = n-1,
paste0(" P < ", min(pvalue)), pos = 4,
cex = 0.8, adj = 0)
points(x = m + 2, y = n-2,
pch = pvSymbols[1], cex = sigSymbolsSize)
text(x = m + 2, y = n-2,
paste0(" P < ", max(pvalue)),
pos = 4, cex = 0.8)
title(main = "heatmap", font.main = 4)
### 格子颜色图注legend
par(fig=c(0.1,0.9,0,1), new = TRUE)
image(x = c(0.9, 1), y = seq(0, 0.3, length.out = 200),
z = matrix(seq(0, 1, length.out = 200), nrow = 1),
col = col_pal, xlim = c(0, 1), ylim = c(0, 1), axes = FALSE,
xlab = NA, ylab = NA)
# 负对数并保留两位小数
data_label <- round(-log(seq(min(data), max(data), length.out = 7)),1)
atLims = seq(0, 0.3, length.out = 7)
axis(side = 4, at = atLims, # 坐标轴位置,刻度线标记的点
tcl = -0.1, # 刻度长度
labels = data_label, # 刻度文字标签
las=2, # 标签是否平行于(=0)或垂直于(=2)坐标轴
lwd = 0.5, cex.axis = 0.5, line = 0.2)
text(x = 0.85, y = 0.2, labels = "-log10(data)",
srt = 90, cex = 0.8, xpd = TRUE)
参考:
https://zhuanlan.zhihu.com/p/505869908
https://www.cnblogs.com/xudongliang/p/6762618.html