Guest User

Simulate and show an animation of correlated datasets

a guest
Aug 2nd, 2015
256
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. set.seed(2015-08-02)
  2. rbivariate <- function(r, mean.x = 0, sd.x=1, mean.y=0, sd.y=1, n=1) {
  3.    z1 <- rnorm(n)
  4.    z2 <- rnorm(n)
  5.    x <- sqrt(1-r^2)*sd.x*z1 + r*sd.x*z2 + mean.x
  6.    y <- sd.y*z2 + mean.y
  7.    return(list(x,y))
  8. }
  9. library(animation)
  10. library(ggplot2)
  11. library(gridExtra)
  12. frames <- 200
  13. saveGIF(
  14.         replicate(frames, {
  15.             r13 <- rbivariate(0.13, n=52)
  16.             r23 <- rbivariate(0.23, n=52)
  17.             r33 <- rbivariate(0.33, n=52)
  18.             r41 <- rbivariate(0.41, n=52)
  19.  
  20.             p13 <- qplot(r13[[1]], r13[[2]], xlab="x", ylab="y", main="0.13") + coord_cartesian(xlim=c(-2,2), ylim=c(-2,2)) + stat_smooth(method="lm", se=FALSE)
  21.             p23 <- qplot(r23[[1]], r23[[2]], xlab="x", ylab="y", main="0.23") + coord_cartesian(xlim=c(-2,2), ylim=c(-2,2)) + stat_smooth(method="lm", se=FALSE)
  22.             p33 <- qplot(r33[[1]], r33[[2]], xlab="x", ylab="y", main="0.33") + coord_cartesian(xlim=c(-2,2), ylim=c(-2,2)) + stat_smooth(method="lm", se=FALSE)
  23.             p41 <- qplot(r41[[1]], r41[[2]], xlab="x", ylab="y", main="0.41") + coord_cartesian(xlim=c(-2,2), ylim=c(-2,2)) + stat_smooth(method="lm", se=FALSE)
  24.            
  25.             grid.arrange(p13, p23, p33, p41)
  26.            }),
  27.     interval = 0.8, ani.width = 900, ani.height = 900,
  28.     movie.name = "/home/gwern/yvain-correlates-visualized.gif")
RAW Paste Data