Ggplot2: set of (non-linear) values ​​for alpha

I would like to plot a 95% mirror density curve and map alpha to density:

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

This works fine, but I would like to make the contrast between the edges and the middle more noticeable, i.e. I want the edges to be almost white, but only the middle part is black. I searched scale_alpha(), but with no luck. Any ideas?

Edit: Ultimately, I would like to build a few raindrops, i.e. individual drops will be small, but the shading should be clearly visible.

+5
source share
3 answers

Thinking about all your answers, I really found exactly what I was looking for. The easiest way is to simply use it scale_colour_gradientnwith a gray vector.

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
0
source

, dens0 alpha, 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..))

enter image description here

, . ( , 0,25):

drf + scale_color_gradient2(midpoint = 0.25)

enter image description here

, dens0, :

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

enter image description here

!. , . , , , , .

+4

Here is a solution using geom_ribbon () instead of 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))

enter image description here

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

enter image description here

See Paul's answer for changing colors.

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)

enter image description here

+3
source

All Articles