How to mark slope changes in LOESS curve using ggplot2?

前端 未结 2 873
无人共我
无人共我 2020-12-29 12:54

I have some time-series data that I\'m fitting a loess curve in ggplot2, as seen attached. The data takes the shape of an \"S\" curve. What I really need to find out is the

2条回答
  •  一生所求
    2020-12-29 13:28

    If you are asking for a way of determining the point where the curve is a maximum (i.e. flat), this is the same as finding the point where the slope of the line is at its maximum (from basic calculus).

    First, read your data:

    christi <- read.table("http://dl.dropbox.com/u/75403/stover_data.txt", sep="\t", header=TRUE)
    

    Next, use loess to fit a smoothed model:

    fit <- loess(org_count~date, data=christi)
    

    Then, predict the values in your range of x-values (with predict.loess), determine the slope (diff is close enough`), and find the

    x <- 200:800
    px <- predict(fit, newdata=x)
    px1 <- diff(px)
    
    which.max(px1)
    [1] 367
    

    Since the start value of x is 200, this means the curve is flat at position 200+367=567.


    If you wanted to plot this:

    par(mfrow=c(1, 2))
    plot(x, px, main="loess model")
    
    plot(x[-1], px1, main="diff(loess model)")
    abline(v=567, col="red")
    

    enter image description here

提交回复
热议问题