Creating an image of a fern leaf in R

I came across this nice fractal image of a fern leaf on this website. There is also an explanation of the method to create such an image. It looked easy enough so I tried to apply this in R. Below is how.

Step 1 – Lists with transformation and translation matrices and vector with probabilities. Try also to change some of the values in these matrices to see how this affects the shape of the figure.

a <- list(matrix(c(0,0,0,0.16),2,2), matrix(c(0.85,0.04,-0.04,0.85),2,2), matrix(c(0.2,-0.26,-0.23,0.22),2,2), matrix(c(-0.15,0.28,0.26,0.24),2,2))

b <- list(matrix(c(0,0),2,1), matrix(c(0,1.6),2,1), matrix(c(0,1.6),2,1), matrix(c(0,0.44),2,1))

c <- c(0.03,0.7,0.16,0.11)

Step 2 – Start coordinates, vector with sample order, and empty data frame where the coordinates will be written to.

d <- c(0.1,0.1)

e <- sample(c(1:4),100000,replace=TRUE, prob=c)

f <- as.data.frame(matrix(rep(0,2*length(e)),length(e),2))

Step 3 – Loop to calculate the coordinates and plot them (output is png file in the home directory)

for(i in 1:length(e)){

d <- (a[e[i]][[1]] %*% d) + b[e[i]][[1]]

f[i,] <- t(d)

}

png(file=”fern.png”, width=8,height=16, units=”cm”,res=300); par(mar=c(0,0,0,0))

plot(f[,1],f[,2], cex=0.1,col=”darkgreen”, pch=19, xaxt=”n”,yaxt=”n”, bty=”n”, main=””)

dev.off()

Not exactly the same as the one shown on the above-mentioned website, but the result does resemble a fern leaf, or  a Christmas tree according to my daughter🙂.

Fern leaf
Click on image for larger version

Creating this image may take a long time if you try to create many more points (this image consists of 100,000 points). I am sure there is a lot of room to optimize the code. I wonder for example how to  avoid the loop. But that is for another time (if you have any suggestion, please let me know).

Update: See this pdf for more detailed explanation to create a fractal resembling a fern leaf.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s