ggplot2:根据填充值为某些点设置alpha = 0

Jar*_*les 10 plot alpha r fill ggplot2

我目前正在开发一个项目,涉及创建与Hadley的ggplot2 0.9.0页面中关于stat_density2d()的示例非常相似的图.

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))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

现在,我正在努力的是一种基本上为所有不在填充范围内的瓷砖关闭alpha(alpha = 0)的方法.因此,在图像中看到的每个灰色瓷砖都应该设置为0.这样可以使图像更好,特别是当覆盖在地图上时.

如果有人有任何建议,我将不胜感激.

jth*_*zel 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")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Ben*_*ker 10

这似乎有效:

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")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述