[R-sig-Finance] Map of the Market

Brahm, David David.Brahm at geodecapital.com
Wed Jun 7 18:05:10 CEST 2006


Kyle Campbell <Kyle.W.Campbell at williams.edu> wrote:
> I am trying to design an R function to display the Map of Market

Here is the essence of a "squarified treemap":

1) First, order the rectangle sizes (areas) from largest to smallest.

2) If the plotting space available is higher than it is wide, we will
   build blocks starting from the bottom, otherwise from the left.
   For concreteness, suppose we are building a block from the left.

3) A block consists of the next "n" available rectangles.  "n" is
   chosen so that the block is as square as possible.

4) Again assuming (w >= h), we fix the width of the block, then fill
   it with rectangles from the bottom up.

5) What we do to create a rectangle depends on a "hook" function.  It
   may be as simple as a call to "rect", or may involve another level
   of treemapping (e.g. of industries within a sector).

6) Repeat from step (2) until all rectangles are created.

### Code begins ###

chop <- function(x) rev( rev(x)[-1] )

simple.hook <- function(z, xl, yl, xu, yu) {
  rect(xl, yl, xu, yu, lwd=3, border="blue")
  text((xl+xu)/2, (yl+yu)/2, z$one, cex=2.5, col="green")
}

squarified.treemap <- function(z, x=0, y=0, w=1, h=1, hook) {
  cz <- cumsum(z$size) / sum(z$size)
  n <- which.min(abs(log(max(w/h, h/w) * sum(z$size) * cz^2/z$size)))
  more <- n < length(z$size)
  a <- c(0, cz[1:n]) / cz[n]
  if (h > w) {
    hook(z[1:n, ], x+w*chop(a), rep(y,n), x+w*a[-1], rep(y+h*cz[n],n))
    if (more) Recall(z[-(1:n), ], x, y+h*cz[n], w, h*(1-cz[n]), hook)
  } else {
    hook(z[1:n, ], rep(x,n), y+h*chop(a), rep(x+w*cz[n],n), y+h*a[-1])
    if (more) Recall(z[-(1:n), ], x+w*cz[n], y, w*(1-cz[n]), h, hook)
  }    
}

z <- data.frame(size=c(5,8,3,12,2,6,7), one=LETTERS[1:7])
z <- z[order(-z$size), ]
plot(0:1, 0:1, type="n", axes=FALSE, xlab="", ylab="")
squarified.treemap(z, hook=simple.hook)

### Code ends ###

-- David Brahm (brahm at alum.mit.edu)



More information about the R-SIG-Finance mailing list