1

I would like to create a table-based heatmap. The answer https://tex.stackexchange.com/a/175035/70170 looks like what I need, but instead of three fixed colors, I'd like to call \cellcolor{} with a color dependent on the cell value.

Here's my attempt:

\documentclass{article}

\usepackage{colortbl} \usepackage{pgfplots}

\begin{document}

\newcommand{\MinNumber}{6}% \newcommand{\MidNumber}{8} % \newcommand*{\MaxNumber}{14}%

\def\zz#1{% \ifdim #1 pt > \MidNumber pt \pgfmathparse{int(100((#1 - \MidNumber)/(\MaxNumber-\MidNumber)))} % \cellcolor{yellow!\pgfmathresult!red} \else \pgfmathparse{int(100((\MidNumber - #1)/(\MidNumber-\MinNumber)))} % \cellcolor{green!\pgfmathresult!yellow} \fi #1}

\begin{table}[] \begin{tabular}{ccc} \zz{6} & \zz{7} & \zz{8} \ \zz{9} & \zz{10} & \zz{11} \ \zz{12} & \zz{13} & \zz{14} \end{tabular} \end{table}

\end{document}

Unfortunately, this does not produce the expected gradient result, but only pure yellow or pure red cells. I printed the \pgfmathresult to check that the computation is correct, and also tried some hardcoded offset like yellow!20!red, which works as well.

I must be overlooking the obvious, but can't figure out what it is. Help from the TeX expert would be much appreciated - thank you!

Note that I am not looking for alternative approaches to creating heatmap tables, but for a way to fix the approach using \colortbl's \cellcolor.

Hanno
  • 155

1 Answers1

1

\cellcolor should be (after expansion) the first item in the cell, with no unexpandable token before it.

You can use \fpeval:

\documentclass{article}

\usepackage[table]{xcolor} \usepackage{pgfplots}

\ExplSyntaxOn

\NewExpandableDocumentCommand{\fpcompareTF}{mmm} { \fp_compare:nTF { #1 } { #2 } { #3 } }

\ExplSyntaxOff

\begin{document}

\newcommand{\MinNumber}{6}% \newcommand{\MidNumber}{8} % \newcommand*{\MaxNumber}{14}%

\newcommand{\zz}[1]{% \fpcompareTF{#1>\MidNumber}{% \cellcolor{% yellow!\fpeval{round(100((#1 - \MidNumber)/(\MaxNumber-\MidNumber)),0)}!red% }% }{% \cellcolor{% green!\fpeval{round(100((\MidNumber - #1)/(\MidNumber-\MinNumber)),0)}!yellow% }% }% #1% }

\begin{table}[htp] \begin{tabular}{ccc} \zz{6} & \zz{7} & \zz{8} \ \zz{9} & \zz{10} & \zz{11} \ \zz{12} & \zz{13} & \zz{14} \end{tabular} \end{table}

\end{document}

enter image description here

egreg
  • 1,121,712