[Tex/LaTex] Parametrize shading in table through TikZ

colorconditionalstablestikz-pgf

I wanted to do some shading in a table according to its values. For example, if you see the table below:

  a  b   c   d 
a 90 10  0   0
b 0  80  10  10
c 0  0   95  5
d 0  10  5   85

I want to shade automatically each numeric cell with a mixture of black and white according to its value. That is, (a,a) = 90 should be something like black!90, and (c,d) = 5 should be black!5. Also, if you can parametrized the shading operation so one can define the color and if we use the value or the complement that would be great.

I was thinking in something like Drawing different tikz shapes parameterized by data from a file, but I cannot see how can one achieve that in a table.

Can you give me some advice on how to achieve such automatic styling?

Best Answer

You could use pgfplotstable and the xcolor package with the [table] option, which gives you the \cellcolor command.

Here's a new style for \pgfplotstabletypeset that colors the cell a different shade of gray according to the cell value, and prints the value in white if the background is more than 50% black.

The command

\pgfplotstabletypeset[color cells]{
 x,a,b,c,d      % The first column needs a name
 a,90,10,0,0
 b,0,80,10,10
 c,0,0,95,5
 d,0,10,5,85
 }

will then give you (shown here with a caption)

\documentclass{article}
\usepackage[table]{xcolor}
\usepackage{pgfplotstable}

\pgfplotstableset{
    color cells/.style={
        col sep=comma,
        string type,
        postproc cell content/.code={%
                \pgfkeysalso{@cell content=\rule{0cm}{2.4ex}\cellcolor{black!##1}\pgfmathtruncatemacro\number{##1}\ifnum\number>50\color{white}\fi##1}%
                },
        columns/x/.style={
            column name={},
            postproc cell content/.code={}
        }
    }
}

\begin{document}
\begin{table}\caption{Correlation or something}
\centering
\pgfplotstabletypeset[color cells]{
x,a,b,c,d
a,90,10.5,0,0
b,0,80,10,10
c,0,0,95,5
d,0,10,5,85
}
\end{table}
\end{document}
Related Question