Filling under a curve using ggplot graphs

I would like to create a graph with a normal function from x = -2 to x = 2, filled with a curve from -2 to 0. I tried with ggplot2

qplot(c(-2, 2), stat="function", fun=dnorm, geom="line") +
+ geom_area(aes(xlim=c(-2,0)),stat="function", fun=dnorm)

But I get this graph fully filled (black) enter image description here

How can I get a plot filled only from -2 to 0?

Other options or packages are welcome.

I also tried only one command with the ggplot parameter and padding, but I can't get it either.
I know that some people do this using polygons, but the result is not so soft and pleasant.

PD: I repeat, the solution I'm looking for does not involve generating x, y coordinates in advance, but it uses a function directly with stat = "function", fun = dnorm or the like. So my question is not a duplicate.

I also tried

ggplot(NULL,aes(x=c(-2,2))) +  geom_area(aes(x=c(-2,0)),stat="function", fun=dnorm, fill="red") +
geom_area(aes(x=c(0,2)),stat="function", fun=dnorm, fill="blue")  

, . , , . geom_ribbon .

0
2

:

ggplot(data.frame(x = c(-2, 2)), aes(x)) +
  stat_function(fun = dnorm) + 
  stat_function(fun = dnorm, 
                xlim = c(-2,0),
                geom = "area") 

enter image description here

+4

dnorm ?

library(ggplot2)
x<-seq(-2,2, 0.01)
y<-dnorm(x,0,1)
xddf <- data.frame(x=x,y=y)
qplot(x,y,data=xddf,geom="line")+
  geom_ribbon(data=subset(xddf ,x>-2 & x<0),aes(ymax=y),ymin=0,
              fill="red",colour=NA,alpha=0.5)+
  scale_y_continuous(limits=c(0, .4))

enter image description here

+2

Source: https://habr.com/ru/post/1685460/


All Articles