在线曲线下填充

Fill under line curve

对于下面的示例数据集,我只想将 y 绘制为一条平滑线,并使用 R 在线下方进行填充。

我能得到平滑的线条,但不能得到颜色填充的曲线。有人可以帮我吗?

date, y
2015-03-11, 71.12
2015-03-10, 34.0
2015-03-09, 11.1
2015-03-08, 9.62
2015-03-07, 25.97
2015-03-06, 49.7
2015-03-05, 38.05
2015-03-04, 38.05
2015-03-03, 29.75
2015-03-02, 35.85
2015-03-01, 30.65

我用来绘制平滑线的代码如下。我无法用颜色

填充线下的部分
y <- df$y
x <- 1:length(y)

plot(x, y, type='n')
smooth = smooth.spline(x, y, spar=0.5)
lines(smooth)

编辑 使用 polygon 函数没有给出预期的结果。阴影区域应低于不高于

的线
with(smooth, polygon(x, y, col="gray"))

通过在多边形周围行进时按顺序列出其边界顶点来描述多边形。

此多边形的边界由曲线 加上右下角和左下角的另外两个顶点 组成。为了帮助您看到它们,我绘制了顶点,根据序列中的位置改变它们的颜色。

这是执行此操作的 R 代码。它使用 predictspline 对象获取曲线的坐标,然后使用连接运算符 c 连接两个额外点的 x 和 y 坐标。为了使填充到轴上,手动设置了绘图范围。

y <- c(71, 34, 11, 9.6, 26, 50, 38, 38, 30, 36, 31)
n <- length(y)
x <- 1:n
s = smooth.spline(x, y, spar=0.5)
xy <- predict(s, seq(min(x), max(x), by=1)) # Some vertices on the curve
m <- length(xy$x)                         
x.poly <- c(xy$x, xy$x[m], xy$x[1])         # Adjoin two x-coordinates
y.poly <- c(xy$y, 0, 0)                     # .. and the corresponding y-coordinates
plot(range(x), c(0, max(y)), type='n', xlab="X", ylab="Y")
polygon(x.poly, y.poly, col=gray(0.95), border=NA)          # Show the polygon fill only
lines(s)
points(x.poly, y.poly, pch=16, col=rainbow(length(x.poly))) # (Optional)