所以我想用这样的颜色来形象化一个矩阵
library(RColorBrewer)
vec = rbinom(10000,1,0.1)
n = sum(vec)
vec = ifelse(vec == 1, rnorm(n), 0)
mat = matrix(vec,100,100)
image(t(mat)[,nrow(mat):1],
col=brewer.pal(8,"RdBu"),
xaxt= "n", yaxt= "n", frame.plot=T,
useRaster = TRUE
)
Run Code Online (Sandbox Code Playgroud)
这给了我情节
但我希望颜色“以 0 为中心”。我的意思是我希望零值是白色,正/负值是红色/蓝色(或蓝色/红色无关紧要)。如果可能的话,有什么想法吗?
bluered包中的函数gplots就是这样做的。您可以将调色板设置为:
library(gplots) # not to be confused with `ggplot2`, which is a very different package
color_palette <- bluered(9) # change the number to adjust how many shades of blue/red you have. Even numbers will assign white to two bins in the middle.
Run Code Online (Sandbox Code Playgroud)
要强制它们在中间居中,您可以使用该heatmap.2函数,也可以使用gplots- 只是不要让它进行任何聚类:
heatmap.2(mat,
Rowv = FALSE,
Colv = FALSE,
dendrogram = 'none',
trace = 'none',
col = bluered, # this can take a function
symbreaks = TRUE, # this is the key value for symmetric breaks
)
Run Code Online (Sandbox Code Playgroud)
要坚持使用该image功能,您需要手动设置休息时间。以下代码将为您提供:
pos_breaks <- quantile(abs(mat), probs = seq(0, 1, length.out = 5))
centered_breaks <- c(rev(-pos_breaks[-1]), pos_breaks)
Run Code Online (Sandbox Code Playgroud)