2015-04-06 168 views
5

我正在嘗試使用ggplot2而不是柵格包圖函數製作柵格圖以獲取一些不相關的原因。在ggplot2中更改柵格圖的顏色

我想縮放顏色,使圖上的最低溫度是藍色,圖上的最高溫度是紅色,而中間範圍是白色。我已經嘗試了ggplot2的許多功能,並且一直未能獲得所需的結果。這就是我想要的:

plot showing desired color ramp from raster package

這裏是我的GGPLOT2代碼的當前狀態:

library(raster) 
library(ggplot2) 
library(scales) 

r = raster() 
r[] = 1:ncell(r) 

df = as.data.frame(r, xy=TRUE) 

the_plot = ggplot(df) + 
    geom_raster(aes(x, y, fill=layer)) + 
    scale_fill_gradient2(low=muted('red'), mid='white', high=muted('blue')) 
print(the_plot) 

其中,而不是期望的顏色漸變,產生這樣的:

ggplot2 scale_fill_gradient2() fail

任何建議,非常感謝!

+0

小心分享一些數據?所以我們可以重新創建情節。您是否嘗試過scale_fill_discrete或scale_fill_hue? – infominer

+0

您是否嘗試將'midpoint'參數設置爲'scale_fill_gradient2'? – Gregor

回答

5

剛剛嘗試過您的示例數據集,下面的代碼適用於我。

the_plot = ggplot(df) + 
    geom_raster(aes(x, y, fill=layer)) + 
    scale_fill_gradientn(colours=c("#0000FFFF","#FFFFFFFF","#FF0000FF")) 
print(the_plot) 

RGB顏色需要調整爲準確的所需的藍色/紅色陰影,但它似乎工作。

plot showing the result