5

我想绘制一条镜像的 95% 密度曲线并将 alpha 映射到密度:

foo <- function(mw, sd, lower, upper) {
x <- seq(lower, upper, length=500)
dens <- dnorm(x, mean=mw, sd=sd, log=TRUE)
dens0 <- dens -min(dens)
return(data.frame(dens0, x))
}

df.rain <- foo(0,1,-1,1)

library(ggplot2)


drf <- ggplot(df.rain, aes(x=x, y=dens0))+
geom_line(aes(alpha=..y..))+
geom_line(aes(x=x, y=-dens0, alpha=-..y..))+
stat_identity(geom="segment", aes(xend=x, yend=0, alpha=..y..))+
stat_identity(geom="segment", aes(x=x, y=-dens0, xend=x, yend=0, alpha=-..y..))
drf

这很好用,但我想让边缘和中间的对比更加突出,即我希望边缘接近白色,只有中间部分是黑色的。我一直在篡改,scale_alpha()但没有运气。有任何想法吗?

编辑:最终,我想绘制几个雨滴,即单个雨滴会很小,但阴影仍应清晰可见。

4

3 回答 3

4

而不是映射dens0alpha,我将其映射到color

drf <- ggplot(df.rain, aes(x=x, y=dens0))+
   geom_line(aes(color=..y..))+
   geom_line(aes(x=x, y=-dens0, color=-..y..))+
   stat_identity(geom="segment", aes(xend=x, yend=0, color=..y..))+
   stat_identity(geom="segment", aes(x=x, y=-dens0, xend=x, yend=0, color=-..y..))

在此处输入图像描述

现在我们仍然有颜色的对比主要存在于尾巴上。使用两种颜色会有所帮助(注意颜色切换为 0.25):

drf + scale_color_gradient2(midpoint = 0.25)

在此处输入图像描述

最后,为了包括dens0值的分布,我将色标的中点基于数据中的中值:

drf + scale_color_gradient2(midpoint = median(df.rain$dens0))

在此处输入图像描述

笔记!:但是,无论您调整数据的方式如何,数据中的最大对比是数据集中更极端的值。试图通过弄乱非线性比例或像我一样调整颜色比例来掩盖这一点,可能会呈现真实数据的虚假画面。

于 2012-07-31T11:00:43.413 回答
3

这是使用 geom_ribbon() 而不是 geom_line() 的解决方案

df.rain$group <- seq_along(df.rain$x)
tmp <- tail(df.rain, -1)
tmp$group <- tmp$group - 1
tmp$dens0 <- head(df.rain$dens0, -1)
dataset <- rbind(head(df.rain, -1), tmp)
ggplot(dataset, aes(x = x, ymin = -dens0, ymax = dens0, group = group, 
  alpha = dens0)) + geom_ribbon() + scale_alpha(range = c(0, 1))

在此处输入图像描述

ggplot(dataset, aes(x = x, ymin = -dens0, ymax = dens0, group = group, 
  fill = dens0)) + geom_ribbon() + 
  scale_fill_gradient(low = "white", high = "black")

在此处输入图像描述

请参阅保罗更改颜色的答案。

dataset9 <- merge(dataset, data.frame(study = 1:9))
ggplot(dataset9, aes(x = x, ymin = -dens0, ymax = dens0, group = group, 
    alpha = dens0)) + geom_ribbon() + scale_alpha(range = c(0, 0.5)) + 
    facet_wrap(~study)

在此处输入图像描述

于 2012-07-31T11:20:07.967 回答
0

在思考你的两个答案时,我实际上找到了我正在寻找的东西。最简单的方法是简单地使用scale_colour_gradientn灰色向量。

library(RColorBrewer)
grey <- brewer.pal(9,"Greys")

drf <- ggplot(df.rain, aes(x=x, y=dens0, col=dens0))+
 stat_identity(geom="segment", aes(xend=x, yend=0))+
 stat_identity(geom="segment", aes(x=x, y=-dens0, xend=x, yend=0))+
 scale_colour_gradientn(colours=grey)
drf
于 2012-08-02T11:10:39.837 回答