# [Tex/LaTex] Is it possible to draw an n by n grid with text in each cell, with a different background shade/colour in each? (confusion matrix)

matricestables

I am making a confusion matrix for a document, and I was wondering if LaTeX has the capabilities to handle this. It is essentially a table, but with background shading corresponding to the value in the table (the shading could be hand-coded).

How can this be done in LaTeX? Is it possible? An example is

Building on Qrrbrbirlbel's answer, the collcell package can be used to automatically apply the color to each cell without the need to explicitly use a macro; a little example (notice particularly the second matrix):

\documentclass{article}
\usepackage[table]{xcolor}
\usepackage{collcell}
\usepackage{hhline}
\usepackage{pgf}

\newcommand\gray{gray}

\newcommand\ColCell[1]{%
\pgfmathparse{#1<.8?1:0}%
\ifnum\pgfmathresult=0\relax\color{white}\fi
\pgfmathparse{1-#1}%
\expandafter\cellcolor\expandafter[%
\expandafter\gray\expandafter]\expandafter{\pgfmathresult}#1}

\newcolumntype{E}{>{\collectcell\ColCell}c<{\endcollectcell}}

\begin{document}

\noindent\begin{tabular}{c*{6}{|E}|}
\multicolumn{1}{c}{} & \multicolumn{1}{c}{hw} & \multicolumn{1}{c}{bx}
& \multicolumn{1}{c}{wk} & \multicolumn{1}{c}{jg} & \multicolumn{1}{c}{cl}
& \multicolumn{1}{c}{rn} \\ \hhline{~*6{|-}|}
ving & 1 & 0 & 0 & 0 & 0 & 0 \\ \hhline{~*6{|-}|}
xing & 0 & 0.92 & 0.08 & 0 & 0 & 0 \\ \hhline{~*6{|-}|}
king & 0 & 0.03 & 0.97 & 0 & 0 & 0 \\ \hhline{~*6{|-}|}
ging & 0 & 0 & 0 & 1 & 0 & 0 \\ \hhline{~*6{|-}|}
ping & 0 & 0 & 0 & 0 & 1 & 0 \\ \hhline{~*6{|-}|}
ning & 0 & 0 & 0 & 0 & 0 & 1 \\ \hhline{~*6{|-}|}
\end{tabular}\par\bigskip

\noindent\begin{tabular}{ *{6}{E}}
0.2 & 0.3 & 0.2 & 0.86 & 0 & 1 \\
0.87 & 0.65 & 0.43 & 0.6 & 1 & 0.3 \\
0.17 & 0.25 & 0.83 & 0.23 & 0.7 & 0.5 \\
0.72 & 0.45 & 1 & 0.5 & 0.43 & 0.85 \\
0.1 & 0.15 & 0 & 0.65 & 0.83 & 0.25 \\
0 & 1 & 0.4 & 0.51 & 0.63 & 0.75 \\
\end{tabular}

\end{document}