Fill under line curve

前端 未结 1 432
南旧
南旧 2021-02-10 01:45

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 c

1条回答
  •  长情又很酷
    2021-02-10 02:14

    Describe a polygon by listing its boundary vertices in order as you march around it.

    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.

    Figure

    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)
    

    0 讨论(0)
提交回复
热议问题