Search code examples
rgraphpolygoncurve

filling color gridient under normal curve in X direction in r


I am trying to shade under curve (contrast to y direction in this post). Just the following is hypothesis of filling direction.

curve(dnorm(x,0,1),xlim=c(-3,3),main='Standard Normal')

enter image description here

I am trying to write a function, where I can fill very small polygons with different colors ( I do not know if this is right approach), then it will look like gradient.

The idea is to extend the following filling of single polygon to n polygons.

codx <- c(-3,seq(-3,-2,0.01),-2)
cody <- c(0,dnorm(seq(-3,-2,0.01)),0)

 curve(dnorm(x,0,1),xlim=c(-3,3),main='Standard Normal')
 polygon(codx,cody,col='red')

I tried to extend it to a function: x1 <- NULL y1 <- NULL

polys <- function ( lwt, up, itn) {
    x1 <- c(lwt,seq(lwt,up, itn),up)
    y1 <- c(0,dnorm(seq(lwt,up,tn)),0)
    out <- list (x1, y1)
    return (out)
    }
out <- polys(lwt = 0, up = 1, itn = 0.1)

library(RColorBrewer)
plotclr <- brewer.pal(10,"YlOrRd")

Neither I could workout the function nor I could brew more colors than 9 this way. Help appreciated.


Solution

  • You can use segments to achieve "roughly" what you want

    x <- seq(from=-3, to=3,by=0.01)
    curve(dnorm(x,0,1), xlim=c(-3,3))
    segments(x, rep(0,length(x)),x,dnorm(x,0,1) , col=heat.colors(length(x)), lwd=2)
    

    enter image description here