2012-04-18 73 views
10

我目前正在研究一個涉及創建與Hadley的ggplot2 0.9.0關於stat_density2d()頁面示例非常相似的圖的項目。ggplot2:根據填充值爲某些點設置alpha = 0

library(ggplot2) 
dsmall <- diamonds[sample(nrow(diamonds), 1000), ] 
d <- ggplot(dsmall, aes(carat, price)) + xlim(1,3) 
d + stat_density2d(geom="tile", aes(fill = ..density..), contour = FALSE) 
last_plot() + scale_fill_gradient(limits=c(1e-5,8e-4)) 

enter image description here

現在,我掙扎是一種基本上把阿爾法關閉(阿爾法= 0)不在填充範圍內的所有瓷磚。因此,在圖像中看到的每個灰色圖塊,alpha都應設置爲0.這會使圖像更好,特別是在覆蓋地圖頂部時。

如果有人有任何建議,這將不勝感激。

+3

灰色區域是由na.value參數scale_fill_gradient控制,但是即使當我指定的透明顏色(如na.value = RGB(1,1,1,0))它變得不透明,所以必須有其他的事情發生。 – Fojtasek 2012-04-18 16:32:52

+0

好吧,所以也許如果我們可以設置scale_alpha_continuous的限制取決於填充值(密度),那麼設置alpha na.value = 0 ... – 2012-04-18 17:28:23

+0

目前爲止還沒有運氣,儘管設置爲'gray90'會使得它看起來*幾乎* OK,因爲這是背景網格的顏色......我真的懷疑這是一個ggplot「問題」(buglet/wishlist?)...可能與https://github.com/hadley/ggplot2有關/ issues/475? – 2012-04-18 21:59:33

回答

9

這似乎工作:

d + stat_density2d(geom="tile", 
    aes(fill = ..density.., 
    alpha=cut(..density..,breaks=c(0,1e-5,Inf))), 
    contour = FALSE)+ 
scale_alpha_manual(values=c(0,1),guide="none") 

enter image description here

+0

完美!謝謝你的幫助,本。 – 2012-04-19 04:21:51

+0

這真棒,幫了我很多。如果可以的話,我會給它3個upvotes。 – cengel 2014-01-30 06:39:07

11

另一種可能性,只是用ifelse,而不是cut

d + stat_density2d(geom="tile", 
    aes(fill = ..density.., alpha = ifelse(..density.. < 1e-5, 0, 1)), 
    contour = FALSE) + 
scale_alpha_continuous(range = c(0, 1), guide = "none") 

enter image description here

+0

這也很好。你能解釋爲什麼僅在'aes(..)'選項中設置'alpha'是不夠的,但爲什麼填充區域的透明度只能通過用'scale_alpha_continuous'設置範圍來控制?例如,我用'alpha = ifelse(.. density .. <1e-5,0,0.7)'和'scale_alpha_continuous(range = c(0,0.7))'使填充區域稍微透明。 – cengel 2014-01-30 17:25:27