Fractal Fern

April 5, 2013
By

(This article was first published on Frank Portman, and kindly contributed to R-bloggers)

I’m gonna share a short code snippet that I thought was interesting. This post is inspired by one of my engineering computation classes at Rice. The program initializes a pair of coordinates ‘z’ and iteratively updates z by matrix multiplication based on some random number generation criteria. After each successive coordinate update, the new ‘z’ is plotted.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
library(ggplot2)

z <- matrix(c(0, 0), nrow = 2)
x <- c()
y <- c()

for (i in 1:40000) {

  r <- runif(1)

  if (r < .01) {
    z <- matrix(c(0, 0, 0, .16), nrow = 2, byrow = T) %*% z
  }

  else if (r < .86) {
    z <- matrix(c(.85, .04, -.04, .85), nrow = 2, byrow = T) %*% z + c(0, 1.6)
  }

  else if (r < .93) {
    z <- matrix(c(0.2, -.26, .23, .22), nrow = 2, byrow = T) %*% z + c(0, 1.6)
  }

  else {
    z <- matrix(c(-.15, .28, .26, .24), nrow = 2, byrow = T) %*% z + c(0, .44)
  }

  x[i] <- z[1]
  y[i] <- z[2]

}

qplot(x, y, size = I(.5)) + theme_bw() + opts(axis.line = element_blank(),
      axis.text.x = element_blank(), axis.text.y = element_blank(),
      axis.ticks = element_blank(), axis.title.x = element_blank(),
      axis.title.y = element_blank()) + scale_x_continuous(breaks = NULL) +
      scale_y_continuous(breaks = NULL) + ggtitle("Fractal Fern")
	

Pretty.

To leave a comment for the author, please follow the link and comment on their blog: Frank Portman.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Sponsors

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)