Rabiscando no R

quinta-feira, 22 de agosto de 20130 comentários

No Econometrics by Simulation encontrei um interessante post sobre umas criações de gráficos no R!

O autor, Francis Smart, está trabalhando em criar funções que gerem gráficos que aparentam terem sido desenhados à mão!



Abaixo você pode conferir o código utilizado parar criar a função doodle e plotar este curioso gráfico!

doodle <- function(
  start=c(0,0), 
  targets = rbind(c(0,10),c(10,10), c(10,0), c(0,0)) ,
  tdist = .25,
  speed = c(0,0),
  accel = .1,
  resis = .005,
  jitter = .0005,
  chncStp = 0) {
  # start - We start with the starting position
  # targ - Points that will be pursued (initially just a square)
  # tdist - How close we need to get to each point before moving on
  # speed - Initial speed
  # accel - How fast does the drawer accelerate towards that point
  # resis - What percentage of speed is lost each round
  # jitter - A normal draw random jitter that moves the writing tool in an unexpected direction.
  # chncStp - There is some chance that the drawing tool will kill all momentum and stop.
 
  # First off I define a function uvect to convert any two sets of points 
  # into a unit vector and measure the distance between the two points.
 
  uvect <- function(p1,p2=NULL) {
    if (is.null(p2)) {
      p2 <- p1[[2]]
      p1 <- p1[[1]]
    }
    list(vect=(p2-p1)/sqrt(sum((p1-p2)^2)), dist=sqrt(sum((p1-p2)^2)))
  }
 
  # Starup parameters
  i <- 1
  plist <- position <- start # plist saves all of the points that the drawing tool has passed through
  vect <- uvect(position,targets[i,])
 
  while(i<=nrow(targets)) {
    # Calculate the appropriate unit vector and distance from end point
    vect <- uvect(position,targets[i,])
    # Remove some amount of speed from previous velocity
    speed <- speed*(1-resis)
    # IF drawer randomly stops remove all speed
    if (rbinom(1,1,chncStp)) speed<-0
    # 
    speed <- speed + accel*vect[[1]] + rnorm(2)*jitter
    position <- position + speed
    plist <- rbind(plist,position)
    vect <- uvect(position,targets[i,])
    if (vect[[2]]<tdist) i <- i+1
  }
  plist
}
 
plist <- doodle()
 
plot(plist, type="n", lwd=3)
lcol <- rainbow(nrow(plist-1))
for (i in 1:(nrow(plist)-1)) lines(plist[c(i:(i+1)),], type="l", lwd=3, col=lcol[i])

Para mais gráficos e posts interessantes recomendo visitar o site dele!
Compartilhe :
 
Support : Creating Website | Johny Template | Mas Template
Copyright © 2011. Estatisti.co - All Rights Reserved
Template Created by Creating Website Published by Mas Template
Proudly powered by Blogger