2012-06-11 67 views
21

我想在ggplot2中製作熱圖。我的玩具數據和代碼是:ggplot2帶有顏色範圍值的熱圖

set.seed(12345) 
dat <- 
    data.frame(
     Row = rep(x = LETTERS[1:5], times = 10) 
    , Col = rep(x = LETTERS[1:10], each = 5) 
    , Y = rnorm(n = 50, mean = 0, sd = 1) 
    ) 
library(ggplot2) 
p <- ggplot(data = dat, aes(x = Row, y = Col)) + 
     geom_tile(aes(fill = Y), colour = "white") + 
     scale_fill_gradient(low = "white", high = "steelblue") 
p 

我想要的配色方案爲這樣的範圍值:

-3 <= Y < -2 ---> Dark Blue 
-2 <= Y < -1 ---> Blue 
-1 <= Y < 0 ---> Light Blue 
0 <= Y < 1 ---> Light Green 
1 <= Y < 2 ---> Green 
2 <= Y <= 3 ---> Dark Green 

任何幫助將得到高度讚賞。謝謝

回答

15

你有幾個這樣的選擇,但這裏有一個作爲一個起點。

首先,使用cutY創建一個因子與適當的範圍:

dat$Y1 <- cut(dat$Y,breaks = c(-Inf,-3:3,Inf),right = FALSE) 

然後繪製使用調色板從RColorBrewer

ggplot(data = dat, aes(x = Row, y = Col)) + 
     geom_tile(aes(fill = Y1), colour = "white") + 
     scale_fill_brewer(palette = "PRGn") 

enter image description here

該顏色方案在低端比藍色更紫色,但它是c我在啤酒調色板中找不到。

如果你想建立你自己的,你可以簡單地使用scale_fill_manual併爲values參數指定所需的顏色矢量。

+0

感謝@joran您的回覆。我想知道如何清除兩塊長方形之間的線條。謝謝 – MYaseen208

+0

@ MYaseen208在'geom_tile'中設置'color =「transparent」''。 – joran

+0

非常感謝@joran。非常感激。 – MYaseen208

38

目前還不清楚您是否想要不連續的顏色,或者您列出的顏色只是Y範圍內的標記。我將展示兩者。

對於離散的顏色,使用Y1作爲joran定義它

dat$Y1 <- cut(dat$Y,breaks = c(-Inf,-3:3,Inf),right = FALSE) 

然後你就可以得到與特定顏色的情節你列出使用手動規模

p <- ggplot(data = dat, aes(x = Row, y = Col)) + 
     geom_tile(aes(fill = Y1)) + 
     scale_fill_manual(breaks=c("\[-Inf,-3)", "\[-3,-2)", "\[-2,-1)", 
           "\[-1,0)", "\[0,1)", "\[1,2)", 
           "\[2,3)", "\[3, Inf)"), 
         values = c("white", "darkblue", "blue", 
            "lightblue", "lightgreen", "green", 
            "darkgreen", "white")) 
p 

我不知道你想要的-3和3以外的顏色,所以我用白色。

如果你想要一個連續的顏色,從負面的藍色到0的白色到正面的綠色,scale_fill_gradient2都可以工作。

ggplot(data = dat, aes(x = Row, y = Col)) + 
    geom_tile(aes(fill = Y)) + 
    scale_fill_gradient2(low="darkblue", high="darkgreen", guide="colorbar") 

enter image description here

如果要顏色的細節控制,使得映射爲 「darkblue以」 第3 「藍以」 第2 「lightblue」 爲1, 「白色」,在0,等等,然後scale_fill_gradientn會爲你工作:

library("scales") 
ggplot(data = dat, aes(x = Row, y = Col)) + 
    geom_tile(aes(fill = Y)) + 
    scale_fill_gradientn(colours=c("darkblue", "blue", "lightblue", 
           "white", 
           "lightgreen", "green", "darkgreen"), 
         values=rescale(c(-3, -2, -1, 
             0, 
             1, 2, 3)), 
         guide="colorbar") 

+0

非常感謝@布萊恩回答。你是ggplot2的嚮導。非常感謝你的幫助。 – MYaseen208