Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill colors in some specific area in R?

Tags:

plot

r

fill

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 2 different colors, say red and blue, on the each side of vertical line but still below two normal density functions. I thought I can use polygon, but failed.

This is the graph without filling colors:

enter image description here

like image 913
Charles Yan Avatar asked Jan 29 '16 20:01

Charles Yan


People also ask

How do you add a color to a point in R?

Change R base plot point shapes To change the color and the size of points, use the following arguments: col : color (hexadecimal color code or color name). For example, col = "blue" or col = "#4F6228" .

How do I color data in R?

In R, colors can be specified either by name (e.g col = “red”) or as a hexadecimal RGB triplet (such as col = “#FFCC00”). You can also use other color systems such as ones taken from the RColorBrewer package.

How do you shade under a graph in R?

The polygon function can be used to shade the area under the density curve. You just need to pass the density object to it and specify a color.

What do the fill and color inputs do in R?

The color attribute is only used for point, line and scatter chart, fill is generally used for bar, column chart, etc. Color adds color to the border to plot whereas fill is to color inside bar/column, etc.


1 Answers

Here's one way:

First, we'll get the parallel minimum of your densities - this is a vector of the top y coordinates for 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

like image 169
Gregor Thomas Avatar answered Sep 18 '22 23:09

Gregor Thomas