Heatmap tables done better, in Sweave and latex

Sun 10 July 2011

Filed under nerdvana

Tags R

 

I wrote before about using heatmap tables to combine the strengths of tables and graphics for nominal data.

Here is a neat approach using Sweave and latex to produce an effect like in the picture.

This latex code is self-contained. Just save it as myfile.Rnw, run Sweave(myfile.Rnw) from inside R and then pdflatex myfile.tex at the command line from inside the same folder.

(Not a latex person myself so some of the commands may be unnecessary.)

The approach uses the residuals from the chisquared test to generate the “surprisingness” for each cell.

Any thoughts on the marginal totals - should they be in colour too? If so, using which residuals?
How would you improve on this?

documentclass[english,a4paper]{article}

usepackage{color}

usepackage{graphicx}

usepackage{geometry}

usepackage[nogin,noae]{Sweave}

usepackage{colortbl}

definecolor{blue1}{rgb}{.8, .8, 1}

definecolor{blue2}{rgb}{.6, .6, 1}

definecolor{blue3}{rgb}{.4, .4, 1}

definecolor{blue4}{rgb}{.2, .2, 1}

definecolor{blue5}{rgb}{0, 0, 1}

definecolor{red1}{rgb}{1, .8, .8}

definecolor{red2}{rgb}{1, .6, .6}

definecolor{red3}{rgb}{1, .4, .4}

definecolor{red4}{rgb}{1, .2, .2}

definecolor{red5}{rgb}{1, 0, 0}

makeatletter

makeatother

SweaveOpts{echo=FALSE}

begin{document}

<<main, echo=FALSE, results=tex, strip.white=FALSE>>=

cellTexMaker=function(Q){

cellTex =Q

cellTex[TRUE]=“”

r=chisq.test(Q)$residuals

cellTex[r< -.6] <- “cellcolor{blue1}” #

cellTex[r< -1] <- “cellcolor{blue2}” #

cellTex[r< -1.5] <- “cellcolor{blue3}” #

cellTex[r< -2] <- “cellcolor{blue4}” #

cellTex[r< -2.5] <- “cellcolor{blue5}” #

cellTex[r> .6] <- “cellcolor{red1}” #

cellTex[r> 1] <- “cellcolor{red2}” #

cellTex[r> 1.5] <- “cellcolor{red3}” #

cellTex[r> 2] <- “cellcolor{red4}” #

cellTex[r> 2.5] <- “cellcolor{red5}” #

cellTex

}

library(Hmisc)

data(HairEyeColor)

P=HairEyeColor[,,2]

Q=addmargins(P)

cellTex =Q

cellTex[TRUE]=“”

cellTex[-5,-5]=cellTexMaker(P)

latex(Q,file = “”, cellTexCmds = cellTex,insert.bottom=

“footnotesize {textcolor{red}{Red} cells contain numbers which are surprisingly high; 

textcolor{blue}{blue} cells contain numbers which are surprisingly low. Stronger colours are more surprising.}“)

@

end{document}


Comments


socialdatablog © Steve Powell Powered by Pelican and Twitter Bootstrap. Icons by Font Awesome and Font Awesome More