How to fill colors in a specific area in R?

Here is the problem:

x<-seq(0,10,length.out = 1000)
y1<-dnorm(x,mean = 2,sd=1)
y2<-dnorm(x,mean = 6,sd=1)
plot(x,y1,type="l")
lines(x,y2)
abline(v=x[380])

The graph is shown below. How can I fill in 2 different colors, for example red and blue, on each side of the vertical line, but still below the two functions of normal density. I thought I could use a polygon, but could not.

This is a graph without colors:

enter image description here

+4
source share
1 answer

Here is one way:

First, we get a parallel minimum of your densities - this is the vector of upper coordinates yfor our polygons.

y = pmin(y1, y2)

# set up your plot as in the question    
plot(x, y1, type="l")
lines(x, y2)

# define a re-usable variable for the vertical line placement
x_vert = 380
abline(v = x[x_vert])

# Now we'll draw 2 polygons, one for the left side, one for the right.
# The first (x,y) pairs of the polygon are just the (x,y) coords of the
# density we're filling to, until the vertical line
# Then we need to connect the "bottom" points, which have coordinates
# (x[x_vert], 0) and (x[1], 0)    
polygon(x = c(x[1:x_vert], x[x_vert], x[1]), 
        y = c(y[1:x_vert], 0, 0),
        col = "blue")
# similar for the right hand polygon, but now going from x_vert to length(x)
polygon(x = c(x[x_vert:length(x)], x[length(x)], x[x_vert]),
        y = c(y[x_vert:length(x)], 0, 0),
        col = "red")

Voila!

enter image description here

+4
source

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


All Articles