Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shade area under a curve [duplicate]

Tags:

r

I'm trying to shade an area under a curve in R. I can't quite get it right and I'm not sure why. The curve is defined by

# Define the Mean and Stdev
mean=1152
sd=84

# Create x and y to be plotted
# x is a sequence of numbers shifted to the mean with the width of sd.  
# The sequence x includes enough values to show +/-3.5 standard deviations in the data set.
# y is a normal distribution for x
x <- seq(-3.5,3.5,length=100)*sd + mean
y <- dnorm(x,mean,sd)

The plot is

# Plot x vs. y as a line graph
plot(x, y, type="l")

The code I'm using to try to color under the curve where x >= 1250 is

polygon(c( x[x>=1250], max(x) ),  c(y[x==max(x)], y[x>=1250] ), col="red")

but here's the result I'm getting enter image description here How can I correctly color the portion under the curve where x >= 1250

like image 645
agf1997 Avatar asked Apr 29 '16 22:04

agf1997


People also ask

How do I shade under a curve 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.

How do I shade between two curves in Matlab?

x2 = [x, fliplr(x)]; inBetween = [curve1, fliplr(curve2)]; fill(x2, inBetween, 'g');

How do you shade a graph in R?

Method 1: Shade a graph using polygon function : In this method, we are calling the polygon function with its argument col passed with the name or the hex code of the color needed to be shaded in the given graph.


1 Answers

You need to follow the x,y points of the curve with the polygon, then return along the x-axis (from the maximum x value to the point at x=1250, y=0) to complete the shape. The final vertical edge is drawn automatically, because polygon closes the shape by returning to its start point.

polygon(c(x[x>=1250], max(x), 1250), c(y[x>=1250], 0, 0), col="red")

enter image description here

If, rather than dropping the shading all the way down to the x-axis, you prefer to have it at the level of the curve, then you can use the following instead. Although, in the example given, the curve drops almost to the x-axis, so its hard to see the difference visually.

polygon(c(x[x>=1250], 1250), c(y[x>=1250], y[x==max(x)]), col="red")
like image 112
dww Avatar answered Oct 25 '22 09:10

dww