How to smooth a curve

I have data like this. Is there a way to smooth my design?

cr <- colorRampPalette(col=c("red", "red", "red", "red"), bias=1)
linecols <- cr(3)
x<-c(-1000.000000,-900.000000,-800.000000,-700.000000,-600.000000,-500.000000,-400.000000,-300.000000,-200.000000,-100.000000,0.000000,100.000000,200.000000,300.000000,400.000000,500.000000,600.000000,700.000000,800.000000,900.000000,1000.000000)
y<-c(0.809524,1.000000,1.333333,1.333333,3.285714,7.761905,13.619048,7.571429,14.809524,3.904762,1.857143,2.285714,4.857143,8.571429,2.000000,1.523810,2.714286,0.857143,1.285714,0.857143,1.380952)
plot(x, y,type="l",main="Average",ylab="Average Profile",col=linecols[1],ylim=c(0.809524,14.809524),xaxt="s",yaxt="s",lwd=2)

      

+3


source to share


3 answers


lines(x, smooth(y))

      

See ?smooth

.

lines(supsmu(x, y))

      



See "supsmu".

Beware, anti-aliasing is the work of the devil.

+9


source


I will be the second to warn @mdsumner about anti-aliasing (internet search for "data smoothing" returns many pages), but I suggest another solution:

plot(lowess(x,y,f=1/3),type="l",col="red")

      



For details see ?lowess

.

enter image description here

+6


source


Many swimming trunks are available.

Here is the smoothing function:

trace.smooth<-function(trace, type="Savitsky-Golay", width=10){

  if(type=="lowess"){
    smooth.trace<-with(clean.trace, lowess(x=1:length(trace),
                                   y=trace,
                                   f=width/length(trace),
                                   delta=width/2))$y
  }

  if(type=="moving-average"){
        moving_average<-function(width=10){
        moving.average<-rep(1,width)/width
        return(moving.average)
      }

      moving.average<-moving_average(width)

      smooth.trace<-filter(trace, moving.average)

  }

  if(type=="Savitsky-Golay"){
      # Savitsky-Golay smoothing function 
    savistsky_golay<-function(width=10){
      x<-1:width-width/2
      y<-max(x^2)-x^2
      sg<-y/sum(y)
      return(sg)
    }

    sg<-savistsky_golay(width)

      smooth.trace<-filter(trace, sg)
  }

  return(smooth.trace)
}

      

Solution using ggplot2

library(ggplot2)

df<-data.frame(x=x, y=y)

qplot(data=df,
      x=x,
      y=y,
      geom=c("line", "point"))+
      geom_smooth(se=F)

      

plot with smooth

you can add method argument to geom_smooth (method = "loess")

method: a method (function) of antialiasing to use eg. lm, glm, gam, loess, rlm

you can fine tune using stat_smooth

+3


source







All Articles