Graphics, Figures & TablesHow can I put different background colors in cells of a table?

Information and discussion about graphics, figures & tables in LaTeX documents.
Post Reply
jukaiser
Posts: 1
Joined: Wed Mar 27, 2019 3:46 pm

How can I put different background colors in cells of a table?

Post by jukaiser »

I'm trying to change the background color of some cells that have values above some limit. For example, if the cell value is higher than 2, then the cell background color should be red. I think I'm very close because I can do it when the table only has numbers. The problem is I don't know how to do it when my table has a row with cells that contain text and the others with numbers. I always got the error "Missing number, treated as zero". When I remove the entire roll with text, I can do it perfectly. But I need this rows with text and I only want to change the background color of cells with numbers.

Anyone can help me?

This is my code:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{tikz}
\usepackage{collcell}

\newcommand*{\MinNumber}{1.0}%
\newcommand*{\MidNumber}{2.0} %
\newcommand*{\MaxNumber}{3.0}%

%Apply the gradient macro
\newcommand{\ApplyGradient}[1]{%
        \ifdim #1 pt > \MidNumber pt
            \pgfmathsetmacro{\PercentColor}{max(min(100.0*(#1 - \MidNumber)/(\MaxNumber-\MidNumber),100.0),0.00)} %
            \hspace{-0.33em}\colorbox{red!\PercentColor!red}{#1}
        \else
            \pgfmathsetmacro{\PercentColor}{max(min(100.0*(\MidNumber - #1)/(\MidNumber-\MinNumber),100.0),0.00)} %
            \hspace{-0.33em}\colorbox{green!\PercentColor!green}{#1}
        \fi
}

\newcolumntype{R}{>{\collectcell\ApplyGradient}c<{\endcollectcell}}
\renewcommand{\arraystretch}{0}
\setlength{\fboxsep}{3mm} % box size
\setlength{\tabcolsep}{0pt}
\begin{document}

\vspace{1cm}
\begin{figure}
\centering
%\includegraphics[scale=0.4]{fig/PNBOIA_vitoria.png} % Include the image placeholder.png
\caption{Metocean forecast results.}
%\caption{Espectro direcional}
%\end{center}
\end{figure}

\begin{table}
\renewcommand{\baselinestretch}{2}
\caption{Metocean Forecast Table.}
\center 
\label{tabela_periodo}
    \begin{tabular}{| c | *{8}{R}}
    \hline
    \textbf{20180807} & \textbf{00h} & \textbf{03h} & \textbf{06h} & \textbf{09h} & %\textbf{12h} & \textbf{15h} & \textbf{18h} & \textbf{21h} \\ \hline
    \textbf{Significant Wave Height (m)}         & 1.31 & 1.26 & 1.25 & 1.27 & 1.57 & 1.90 & 2.09 & 1.93 \\ \hline
    \textbf{Peak Period (s)}         & 8.8 & 8.7 & 8.8 & 9.5 & 9.9 & 5.7 & 6.2 & 6.5 \\ \hline
    \textbf{Peak Direction (degree)}         & 130 & 130 & 130 & 135 & 136 & 191 & 183 & 172 \\ \hline
    \textbf{Wind Speed (m/s)}     & 1.0 & 1.1 & 3.0 & 7.4 & 8.9 & 10.4 & 10.9 & 8.2 \\ \hline
    \textbf{Wind Direction (degree)}     & 36 & 359 & 261 & 224 & 199 & 194 & 188 & 170 \\ \hline
    \textbf{Tide} & 1.09 & 0.65 & 0.33 & 0.82 & 1.26 & 0.91 & 0.43 & 0.73\\ \hline
    \end{tabular}
\end{table}



\end{document}

Recommended reading 2024:

LaTeXguide.org • LaTeX-Cookbook.net • TikZ.org

NEW: TikZ book now 40% off at Amazon.com for a short time.

And: Currently, Packt sells ebooks for $4.99 each if you buy 5 of their over 1000 ebooks. If you choose only a single one, $9.99. How about combining 3 LaTeX books with Python, gnuplot, mathplotlib, Matlab, ChatGPT or other AI books? Epub and PDF. Bundle (3 books, add more for higher discount): https://packt.link/MDH5p

Ijon Tichy
Posts: 640
Joined: Mon Dec 24, 2018 10:12 am

How can I put different background colors in cells of a table?

Post by Ijon Tichy »

You could try, e.g.,

Code: Select all

\multicolumn{1}{c}{Text}
for the text cell.
Sorry, but I can no longer participate here as the administrator is trampling on my wishes on one of his other platforms. :cry:
rais
Posts: 419
Joined: Sun Nov 16, 2014 8:51 pm

How can I put different background colors in cells of a table?

Post by rais »

well, my first reaction was `why not let LaTeX do it automagically?'
The first thing this \ApplyGradient of yours should do: check, if parameter given is a decimal (or real) number. xstring's \IfDecimal seemed perfect for the job.\textbf within it's argument threw me off course, though.
Ok, never mind, I just let \ApplyGradient decide, if the cell contents should be bold (string) or not (number).
Easy.
Come to think of it, all the other \textbf in the first column could be replaced by a single directive in the column specification (prepend >{\bfseries} to the first column specifier, c).
And what's with these \colorbox commands for colring a cell? I'd use \cellcolor, then I don't need to fiddle around with \tabcolsep and the like.
And twice the same color around \PercentColor? That looked a bit fishy to me...
Anyway, after putting some code in working order

Code: Select all

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[table]{xcolor}
\usepackage{tikz}
\usepackage{collcell}
\usepackage{xstring}
 
\newcommand*{\MinNumber}{1.0}%
\newcommand*{\MidNumber}{2.0} %
\newcommand*{\MaxNumber}{3.0}%
\newcommand*\mynum{}% used inside \ApplyGradient; just checking if it exists already

%Apply the gradient macro
\newcommand{\ApplyGradient}[1]{%
    \IfDecimal{#1}{%
      \edef\mynum{#1}%
      \ifdim #1 pt > \MaxNumber pt\relax
        \edef\mynum{\MaxNumber}%
      \else
        \ifdim #1 pt < \MinNumber pt\relax
          \edef\mynum{\MinNumber}%
        \fi
      \fi
      \ifdim \mynum pt > \MidNumber pt
        \pgfmathsetmacro{\PercentColor}{max(min(100.0*(\mynum - \MidNumber)/(\MaxNumber-\MidNumber),100.0),0.00)}%
        \xdef\PercentColorr{\PercentColor}% must be global here if used in \cellcolor
        \cellcolor{red!\PercentColorr!yellow}#1%<- to have sth. of a `gradient'
      \else
        \pgfmathsetmacro{\PercentColor}{max(min(100.0*(\MidNumber - \mynum)/(\MidNumber-\MinNumber),100.0),0.00)}%
        \xdef\PercentColorr{\PercentColor}% must be global here if used in \cellcolor
        \cellcolor{green!\PercentColorr!yellow}#1%
      \fi	% \MinNumber < #1 <= \MaxNumber
    }{\textbf{#1}}% else it's not a decimal
}
 
\newcolumntype{R}{>{\collectcell\ApplyGradient}c<{\endcollectcell}}
\begin{document}
 
\begin{table}
\renewcommand{\arraystretch}{2}
\caption{Metocean Forecast Table.}
\centering % `center' is defined as an environment
\label{tabela_periodo}
  \begin{tabular}{|>{\bfseries} c | *{8}{R}}
    \hline
    20180807 & 00h & 03h & 06h & 09h & 12h & 15h & 18h & 21h \\ \hline
    Significant Wave Height (m)  & 1.31 & 1.26 & 1.25 & 1.27 & 1.57 & 1.90 & 2.09 & 1.93 \\ \hline
    Peak Period (s) & 8.8 & 8.7 & 8.8 & 9.5 & 9.9 & 5.7 & 6.2 & 6.5 \\ \hline
    Peak Direction (degree) & 130 & 130 & 130 & 135 & 136 & 191 & 183 & 172 \\ \hline
    Wind Speed (m/s) & 1.0 & 1.1 & 3.0 & 7.4 & 8.9 & 10.4 & 10.9 & 8.2 \\ \hline
    Wind Direction (degree) & 36 & 359 & 261 & 224 & 199 & 194 & 188 & 170 \\ \hline
    Tide & 1.09 & 0.65 & 0.33 & 0.82 & 1.26 & 0.91 & 0.43 & 0.73\\ \hline
\end{tabular}
\end{table}

\end{document}
I seriously doubt you'll be happy with it...let me put it this way: do you really want to apply the same colors with the same limits to `Significant Wave Height' and, say, Wind Speed? I mean, 3 m may be a high wave, but 3 m/s is barely more than a light breeze...
Perhaps you should consider swapping columns with rows of this table (for using collcell) or forget collcell for this table (your columns don't contain stuff you could `collect' this way) and use your \ApplyGradient directly in the (few) cells where you actually need it. That seems to me less work than applying a \multicolumn to every cell you don't want colored this way.
Then again, I may be mistaken...

KR
Rainer
Post Reply