2013-05-07 116 views
2

我有一個數據框,它包含此日期的日期和狀態。狀態範圍從-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

請給我們提供一個可重複的例子,即產生圖形所需的代碼和數據,現在我們甚至不知道你使用哪個函數或圖形庫來創建圖形。 – 2013-05-07 09:46:16

+0

它不是關於特定的代碼或圖形庫。老實說如果你使用'heatmap,image或ggplot',我不在乎。我的問題是否有可能在其中任何一箇中做這樣的映射 – Windys 2013-05-07 10:18:26

+0

如果我們有一個數據樣本和一個你想得到的具體例子,回答要容易得多(而且要更快)。 – juba 2013-05-07 10:38:18

回答

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 
2

你可以從gplots包試試heatmap.2()功能,並創建自己的顏色調色板一樣

my_palette <- c("gray","white","green","blue"),然後您可以作爲參數使用的col參數

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

假設您的數據已適當縮放。

我在我的書Heat Maps in R: How-To中簡單地觸及了定製熱圖顏色的這個話題。然而,當前的包還沒有一個真正的「好」的解決方案,但它更像變通:(