2

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!

bluepole
  • 323
  • 1
  • 12
  • 1
    http://lenkiefer.com/2020/06/25/gradient-shading-with-ggplot2/ – mrhellmann Apr 05 '21 at 01:53
  • 1
    May also be worth noting some [New Features in the R Graphics Engine](https://developer.r-project.org/Blog/public/2020/07/15/new-features-in-the-r-graphics-engine/index.html), including gradient fills. – Henrik Apr 05 '21 at 03:44

1 Answers1

1

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

arvi1000
  • 9,393
  • 2
  • 42
  • 52