具有离散值的热图/图像

时间:2013-05-07 09:44:56

标签: r graphics

我有一个数据框,它包含此日期的日期和状态。状态范围从-1到2.我想创建一个热图(按周的天数和一年中的星期数),这不是问题。

我的问题是我想要以下颜色映射:

-1 => gray
0 => white
1 => blue
2 => green

有什么想法吗?谢谢!

修改 正如我所要求的那样,请求示例代码,它对我来说不起作用:

breaks <- seq(-2,2,1)
pal <- c("gray","white","green","blue")
data <- sample(-1:2, 5*6, replace=T)
m <- matrix(unlist(data),ncol=6)
m
image(m,
      col = c("gray","white","green","blue"),
      breaks = c(-2,-1,0,1,2)
      )

2 个答案:

答案 0 :(得分:2)

您可以尝试heatmap.2()包中的gplots功能并创建自己的调色板,如

my_palette <- c("gray","white","green","blue"),然后将其用作col参数

的参数

heatmap.2(..., col = my_palette, ...

假设您的数据已适当缩放。

我在本书Heat Maps in R: How-To中简要介绍了定制热图颜色的主题。然而,对于目前的套餐,并没有真正好的&#34;解决方案,但更像是解决问题:(

答案 1 :(得分:1)

以下似乎可以做你想做的事:

set.seed(14)
a<-matrix(floor(runif(21)*4)-1,nrow=7)
col<-c("grey","white","blue","green")
image(1:8,1:4,a,col=col)

对于gplot版本:

#color scale
col<-c("red","orange","grey","lightblue","darkblue")
#creating the dataframe for 3 example weeks
(d<-t(matrix(c(1,1,2,3,2,3,4,
    2,1,2,2,3,4,4,
    5,3,2,4,5,4,5),nrow=3,byrow=TRUE)))
df<-data.frame(day=rep(1:7,3),week=rep(1:3,each=7),werte=as.numeric(d))
#the ggplot
p<-ggplot(df,aes(x=day,y=max(df$week)+1-week))+
    #tile layer
    geom_tile(aes(fill=factor(werte))) +
    #setting the color
    scale_fill_manual(
        values=col,
        breaks=c("1","2","3","4","5"),
        labels=c("one","two","three","four","five"))

p