首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用RColorBrewer使颜色在0附近居中

使用RColorBrewer使颜色在0附近居中
EN

Stack Overflow用户
提问于 2018-05-18 03:23:24
回答 3查看 2.7K关注 0票数 5

所以我想要可视化一个矩阵,它有这样的颜色

代码语言:javascript
复制
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为白色,正值/负值为红/蓝(或蓝/红,没关系)。如果这是可能的,有什么想法吗?

EN

回答 3

Stack Overflow用户

发布于 2018-05-18 03:27:19

gplots包中的函数bluered可以做到这一点。您可以将调色板设置为:

代码语言:javascript
复制
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函数-只是不要让它进行任何聚类:

代码语言:javascript
复制
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函数,您需要手动设置分隔符。下面的代码将为您实现这一点:

代码语言:javascript
复制
pos_breaks <- quantile(abs(mat), probs = seq(0, 1, length.out = 5))
centered_breaks <- c(rev(-pos_breaks[-1]), pos_breaks)
票数 2
EN

Stack Overflow用户

发布于 2018-05-18 11:29:43

这是一个不需要任何额外包的解决方案。在您的代码中,您没有将来自vec变量的值分配给八个颜色箱中的任何一个。您需要将vec数组分成8个存储箱,然后为每个存储箱分配颜色,然后绘制:

代码语言:javascript
复制
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)

票数 2
EN

Stack Overflow用户

发布于 2018-05-18 03:47:44

除了heatmap2,您还可以使用pheatmap

代码语言:javascript
复制
library(pheatmap)
pheatmap(mat,
         color = brewer.pal(7,"RdBu"),
         border_color = NA,
         cluster_rows = FALSE,
         cluster_cols = FALSE)

如果愿意,您还可以使用legend = FALSE隐藏图例,这将产生与图像调用类似的结果,但白色为0。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50399121

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档