Using R to create brick block graphs

R provides powerful graphics functions. We can use it to draw very complicated and beautiful graphs. Here provides a complete solution to draw brick block graph in R. The function name is brickblock that takes a matrix, graph height, a vector of x-labels, and groupname as inputs. The length of vector should be same as the second dimension of the matrix. The following lists the function code.

brickblock <- function(m, height, xlabs, groupname)
{
	mdim <- dim(m); # dimmension of the input matrix
	margin <- 30;  # default margin
	padding <- 5;

	# create a new matrix filled with 0
	m1 <- matrix(0, mdim[1]+1, mdim[2])
	## relative percentage of height
        for (i in 1:mdim[2]) { m1[1:mdim[1],i] <- m[,i]/sum(m[,i]) }
	## height of each rectangles
	m1 <- m1 * height
	## vertical position
	for (j in (mdim[1]-1):1) { m1[j,] = m1[j,] + m1[j+1,] }
	m1[mdim[1]+1,] <- rep(0,mdim[2])
	m1 <- m1 + margin
	v1 <- m1[2:(mdim[1]+1),]
	v2 <- m1[1:mdim[1],] - padding

	## width of rectangles
	rectwidth = height / mdim[2]
	## horizontal positions
	h1 <- rep(0, mdim[2])
	h2 <- h1
	for (i in 1:mdim[2])
	{
	    h1[i] <- margin + (i - 1) * rectwidth
	    h2[i] <- margin + (i) * rectwidth - padding ## leave a space between two rectangles
	}

	## an example showing colouring and shading
	plot(c(margin, margin+height), c(margin, margin+height), type= "n", xlab="", ylab="", axes=FALSE)
	for (i in 1:mdim[2])
	{
	    for (j in 1:mdim[1])
	    {
	        rect(h1[i],v1[j,i],h2[i],v2[j,i], col="grey", border="black") # coloured
	        text(h1[i]+15, v1[j,i]+11, j, col="white");
	    }
	    text(h1[i]+15, v2[1,i]+11, xlabs[i])
	}
	mtext(groupname, side=2, line=0, cex=1.6);
}

To use the function is pretty simple. First create a matrix and then call the brickblock function like the following.

x<-matrix(c(18,8,10,8,14,19,12,3,14,3,11,17,18,7,11,12,64,37,44,40),4)
brickblock(x, 500, c("2CC", "2SC", "1CC", "1SC", "Total"),"Cluster");

It will draw a graph similar to the following.
brickblock

  • Share/Bookmark

Leave a Response

You must be logged in to post a comment.