您的位置:首页 > 其它

R绘制动态曲线

2013-12-01 11:32 204 查看
使用R语言绘制动画可以方便地观察到数据的变化行为。以之前Chrome在收集页面资料时使用的指数平滑算法为例,绘制一个在不同系数且目标值不断变化(应用场景不是页面访问统计)的情况下的曲线逼近行为。

首先要确保在R中安装了animation包, 如果需要保存成GIF动画,还需要安装ImageMagick。GIF的每一帧是基于一个plot操作的。

下面是一个示例代码:

library(animation)
ani.options(interval = 0.2)

#生成GIF
generateGIF<-function(coeff,loopingCount){
  layout(matrix(c(1, rep(2, 5)), 6, 1))
  saveGIF(generatePlots(coeff,loopingCount))
}

#动画绘制函数
generatePlots<-function(coeff,loopingCount){
  oopt = ani.options(interval = 0.2, nmax = loopingCount)
  
  #初始化绘图,并指定座标范围
  plot(0,0,xlim = c(0,ani.options("nmax")), ylim = c(0, 3500),col='blue',xlab="black:target value, red:actual value",ylab="Values")
  
  tgtValues<-c(0)
  newValues<-c(0)
  posValues<-c(0)
  
  oldValue=0

  for (i in 2:loopingCount) {
    tgtValues[i]=1000+rnorm(1,mean=500,sd=800)  
    newValues[i] = tgtValues[i]*coeff+newValues[i-1]*(1-coeff)
    posValues[i] = i
    
    plot(0,0,xlim = c(0,ani.options("nmax")), ylim = c(0, 3500),col='blue',xlab="black:target value, red:actual value",ylab="Values")
    points(posValues,tgtValues,col="black")
    points(posValues,newValues,col="red")
    lines(posValues,newValues,col="red")
    
    ani.pause() 
  }
}


*CSDN上的GIF都是死的,只能放到别处了!

效果图
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: