所以我想要可视化一个矩阵,它有这样的颜色
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
)这就给了我一个情节

但我希望颜色“以0为中心”。我的意思是,我希望值0为白色,正值/负值为红/蓝(或蓝/红,没关系)。如果这是可能的,有什么想法吗?
发布于 2018-05-18 03:27:19
gplots包中的函数bluered可以做到这一点。您可以将调色板设置为:
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.要强制它们居中,也可以在gplots中使用heatmap.2函数-只是不要让它进行任何聚类:
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
)要继续使用image函数,您需要手动设置分隔符。下面的代码将为您实现这一点:
pos_breaks <- quantile(abs(mat), probs = seq(0, 1, length.out = 5))
centered_breaks <- c(rev(-pos_breaks[-1]), pos_breaks)发布于 2018-05-18 11:29:43
这是一个不需要任何额外包的解决方案。在您的代码中,您没有将来自vec变量的值分配给八个颜色箱中的任何一个。您需要将vec数组分成8个存储箱,然后为每个存储箱分配颜色,然后绘制:
library(RColorBrewer)
vec = rbinom(10000,1,0.1)
n = sum(vec)
vec = ifelse(vec == 1, rnorm(n), 0)
mat = matrix(vec,100,100)
#cut the original data into 9 groups
cutcol<-cut(vec, 9)
#Create color palette with white as the center color
colorpal<-brewer.pal(8,"RdBu")
colorpal<-c(colorpal[1:4], "#FFFFFF", colorpal[5:8])
#assign the data to the 9 color groups
color<-colorpal[cutcol]
#create the color matrix to match the original data
colormat<-matrix(color,100,100)
#plot with the assigned colors
image(t(mat)[,nrow(mat):1],
col=colormat,
xaxt= "n", yaxt= "n", frame.plot=T,
useRaster = TRUE
)
#check color assignment
#hist(vec)
#hist(as.numeric(cutcol), breaks=8)

发布于 2018-05-18 03:47:44
除了heatmap2,您还可以使用pheatmap
library(pheatmap)
pheatmap(mat,
color = brewer.pal(7,"RdBu"),
border_color = NA,
cluster_rows = FALSE,
cluster_cols = FALSE)如果愿意,您还可以使用legend = FALSE隐藏图例,这将产生与图像调用类似的结果,但白色为0。
https://stackoverflow.com/questions/50399121
复制相似问题