3

I am using the colortbl package to color the cells of a table. I want to be able to color a cell depending on the value in the cell. In my specific case, I'd like to enter a number between 30 & 90 and color the cell in a shade of gray. I used the fp package to create a command that displays the value of the argument in a colored cell as shown in the MWE below.

\documentclass{article}
\usepackage{colortbl}
\usepackage{fp}

\newcommand{\colorcell}[1]{%
\FPeval{grayshade}{1.171-0.00857*#1}%
\cellcolor[gray]{\grayshade}#1}

\begin{document}

\begin{tabular}{ccc}
\cellcolor[gray]{.4}85 & \cellcolor[gray]{.8}85\\
\colorcell{73} & 0
\end{tabular}
\end{document}

However, this gives me an error that \grayshade is an undefined control sequence. I can rewrite the code to know that \grayshade is defined; it seems that colortbl isn't liking it for some reason.

How can I fix my code to make this work?

A solution probably exists using things like pgf/Tikz, and I am open to these, but I'd also like to see how this should work.

GregH
  • 3,499

2 Answers2

3

The \cellcolor macro doesn't expand its colour argument. Below I've expanded it using \edef\x{\noexpand\cellcolor...}\x in order to guarantee that \graycolor is expanded to the value calculated by \FPeval:

enter image description here

\documentclass{article}
\usepackage{colortbl}
\usepackage[nomessages]{fp}

\newcommand{\colorcell}[1]{%
  \FPeval\grayshade{1.171-0.00857*#1}%
  \edef\x{\noexpand\cellcolor[gray]{\grayshade}}\x #1}

\begin{document}

\begin{tabular}{ccc}
  \cellcolor[gray]{.4}85 & \cellcolor[gray]{.8}85 \\
  \colorcell{73} & 0
\end{tabular}

\end{document}
Werner
  • 603,163
1

The definition of \grayshade is not expanded when passed to \cellcolor and is not longer available when the cell colour is applied. To ensure its availability, we can create a global, expanded definition \xdef\tempa{\grayshade} to hold the value calculated by FP.

\documentclass{article}
\usepackage{colortbl}
\usepackage{fp}

\newcommand{\colorcell}[1]{%
  \FPeval{\grayshade}{1.171-0.00857*#1}%
  \xdef\tempa{\grayshade}%
  \cellcolor[gray]{\tempa}#1%
}

\begin{document}

\begin{tabular}{ccc}
\cellcolor[gray]{.4}85 & \cellcolor[gray]{.8}85\\
\colorcell{73} & 0
\end{tabular}
\end{document}

4 shades of grey

cfr
  • 198,882