bluepole
bluepole

Reputation: 345

How to continuously vary transparency?

Suppose we create a colored band in R:

library(ggplot2)
dev.new(width=6, height=3)
ggplot(data.frame(20,20)) +
  geom_rect(aes(xmin=0, xmax=100, ymin=0, ymax=50), fill="blue")

enter image description here

I would like to continuously vary the transparency of the band along the y-axis with the alpha value normally distributed:

dnorm(y - 25) / 12.5) / dnorm(0)

How to achieve this? Thanks!

Upvotes: 2

Views: 55

Answers (1)

arvi1000
arvi1000

Reputation: 9582

You could plot it as a bunch of discrete rectangles where alpha varies with y, according to the function you want.

library(ggplot2)
# make this bigger for smaller rects/smoother gradient
n_rects <- 51

dat <- data.frame(y=seq(0, 50, length.out = n_rects))
dat$alpha <- dnorm((dat$y - 25) / 12.5) / dnorm(0)
ggplot(dat) +
  geom_rect(xmin=0, xmax=100, 
            aes(ymin=y, ymax=y+1, alpha=alpha), fill="blue")

enter image description here

Upvotes: 1

Related Questions