1

I would like to color the cells of a tabular environment as a heatmap, like Unas's solution at Parametrize shading in table through TikZ, but I have negative numbers in the table. I would like to set 0 shade for those cells, but I am not able to set up the if condition appropriately.

I can use the if condition to calculate the "shade" variable well, but it is not allowed to propage the result to a function, if the original number is negative.

Please consider the MWE below. I get "17: Missing number, treated as zero. [\end]" and "17: Illegal unit of measure (pt inserted). [\end]" errors if I try to uncomment line 9 and line 16 in the same time.

\documentclass{article}
\usepackage{xcolor,colortbl}
\usepackage{xintexpr}
\newcommand{\cca}[1]{%
 \gdef\shade{\ifnum\numexpr#1<0\relax {\xinttheiexpr 0\relax}\else#1\fi}
 \shade 
 %\ccadoit[10]{#1}% it works
% \ccadoit[0]{#1}% it works
 \ccadoit[\shade]{#1}% it works only for \cca{nonnegative_number}
}
\def\ccadoit[#1]#2{\cellcolor{brown!#1}{ #2}}
\begin{document}
\begin{tabular}{r}
\cca{10} \\ % it works
\cca{0} \\ % it works
\cca{-10} \\ % it does not work with \ccadoit[\shade]{#1}
\end{tabular}
\end{document}

2 Answers 2

1

\relax is not expandable; you have to make sure everything is expandable in the calculation. To that end, I dropped \relax after the numeral comparison in lieu of a space (which should stop the scanning for numbers).

enter image description here

\documentclass{article}

\usepackage[table]{xcolor}

\newcommand{\shade}[1]{\ifnum\numexpr#1<0 0\else#1\fi}
\newcommand{\cca}[1]{%
  \ccadoit[\shade{#1}]{#1}%
}
\def\ccadoit[#1]#2{\cellcolor{brown!#1}{ #2}}

\begin{document}

\begin{tabular}{rrrr}
  \cca{100} & \cca{90} & \cca{80} & \cca {70} \\
  \cca {60} & \cca{50} & \cca{40} & \cca {30} \\
  \cca {20} & \cca{10} & \cca{ 0} & \cca{-10}
\end{tabular}

\end{document}
1

The problem is that \shade is not expanded when it is used by inside \cellcolor. A better approach is define \shade inside the \if-statement, instead of having the \fi-statement inside the definition of \shade. This said, your definition is unnecessarily complicated: using \gdef\shade{\ifnum#1<0 0\else#1\fi} in your code works fine.

Rather than defining \cca and \ccadoit it is more efficient to use just one macro:

enter image description here

\documentclass{article}
\usepackage{xcolor,colortbl}
\newcommand{\cca}[1]{%
  \ifnum#1<0\cellcolor{red!10}{#1}\else\cellcolor{brown!#1}{#1}\fi
}
\begin{document}
  \begin{tabular}{r}
    \cca{100} \\ % it works
    \cca{10} \\ % it works
    \cca{0} \\ % it works
    \cca{-10} \\ % it does not work with \ccadoit[\shade]{#1}
  \end{tabular}
\end{document}

to produce:

1
  • Your solution works also, but Werner's solution was more helpful for me by pointing out that \relax is not expandable in \shade.
    – antale
    Nov 12, 2016 at 15:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .