### How to plot a table of values in R

Displaying a table of values in a plot is often a useful supplement to the graphs presented. In addition, plotted tables can be output as png or pdf files. The following is a table plotted to a png file using R.

Plotting is done by

1. Creating a blank plotting surface with coordinates for placing the row and column elements.
2. Placing rectangles and text for the row and column headers
3. Placing rectangles for the table values

The function implementing these steps follows

``` plot_table <- function(d, colors, marginColor,main="", text.cex=1.0) { plot(c(-1,ncol(d)),c(0,nrow(d)+1), type="n", xaxt="n", yaxt="n", xlab="",ylab="",main=main, bty="n") for (c in 1:ncol(d)) { rect(c-1, nrow(d), c, nrow(d) + 1, col=marginColor) text(c-.5,nrow(d) +.5,colnames(d)[c], cex=text.cex) } for (r in 1:nrow(d)) { rect(-1, r-1, 0, r, col=marginColor) text(-.5, r-.5,rownames(d)[nrow(d) - r + 1], cex=text.cex) } for (r in 1:nrow(d)) for (c in 1:ncol(d)) { rect(c-1, r-1, c, r, col=colors[nrow(d) - r + 1,c]) text(c-.5,r-.5,d[nrow(d) - r + 1,c], cex=text.cex) } } ```

Demo code to call the function follows

``` d <- matrix(round(runif(12*5)-.5,3), ncol=12) colnames(d) <- c("jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec") rownames(d) <- as.character(2011:2015) colors <- matrix(sapply(d, function(x) ifelse(x < 0, "orange","green")),ncol=ncol(d)) par(mar=c(0,0,1,0)) plot_table(d, colors, "gray",main="returns", text.cex=0.8) ```