线下填充 [英] Fill under line curve

查看:100
本文介绍了线下填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

For the sample dataset below, I would like to just plot the y as a smooth line with fill under the line using R.

我能够得到平滑线而不是颜色填充曲线。有人可以在这里帮助我吗?

I am able to get smooth line but not the color filled curve. Could someone please help me here?

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

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

The code I used to plot the smooth line is as follows. I am unable to get fill the portion under the line with a color

y <- df$y
x <- 1:length(y)

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

编辑
使用多边形功能无法提供预期的效果。阴影区域应位于不高于该线的行之下

EDIT Using the polygon function does not give what is expected. The shaded area should be below the line not above

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

推荐答案

通过按顺序列出其边界顶点来描述多边形

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

This polygon's boundary consists of the curve plus two more vertices at the bottom right and bottom left. To help you see them, I have overplotted the vertices, varying their colors by position in the sequence.

这是完成此操作的 R 代码。它使用 predict spline 对象获取曲线的坐标,然后将其的x和y坐标与使用串联运算符 c 的两个额外点。

Here is the R code that did it. It used predict to obtain coordinates of the curve from the spline object, then adjoined the x- and y-coordinates of the two extra points using the concatenation operator c. To make the filling go to the axis, the plot range was manually set.

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)

这篇关于线下填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆