曲线下的阴影区域

13

我试图在R中给曲线下方着色。 我做得不太对,也不确定原因。 曲线由定义

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

情节是

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

我正在使用的代码尝试对x>=1250的曲线下方着色是:

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

但这是我得到的结果 在此输入图像描述 如何正确着色曲线下x >= 1250的那部分

1个回答

25

您需要按照曲线的x、y点与多边形对齐,然后沿着x轴返回(从最大的x值到x=1250,y=0的点),以完成形状。最后一个垂直边缘将自动绘制,因为多边形通过返回到起点来关闭形状。

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

这里输入图片描述

如果你想将阴影下降到x轴以下,而是希望它保持在曲线的水平上,则可以使用以下代码。尽管在给出的示例中,曲线几乎下降到x轴,因此在视觉上很难看到差异。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接