Shade area under a curve [duplicate]

2020-08-21 08:54发布

问题:

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 How can I correctly color the portion under the curve where x >= 1250

回答1:

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")

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")