[Tex/LaTex] Table with colored rows alternating every n rows

colortables

I'd like to create a table where the background color of the rows changes every n>1 rows. I have seen in wikibooks how alternate rows can have different colors and I have looked at one xcolor documentation I found online at math.washginton.edu but I can't figure out how I can have the rowcolor to change every n rows, say every 5 rows.

Also, would it possible to define some sequence, say {4,9,11..} which will tell LaTeX at which row # to switch colors? That way if my observations are unbalanced then I can still highlight the backgrounds differently. What I mean by this is that if I have 3 rows of data from model-1 and 5 rows of data from Model-2 and 2 rows of data from Model-3 then the first 3 rows of my table can be white, the next 5 can be gray and the next 2 rows can be white again and so on..for improved readability, which I need because I have a ton of numbers, which I guess most tables have. 🙂

Right now I am laboriously writing \rowcolor{} in front of any row that I'd like colored.

Any help will be greatly appreciated.

Best Answer

This shows one way of adding a counter that increments every row and then having an arbitrary set of tests to switch colours on some condition. This starts off with no background switches to green on row 4 stays green until row 7 when it switches to blue, goes back to no background at row 13, then cycles round again every 20 rows.

enter image description here

\documentclass{article}

\usepackage{colortbl}
\newcounter{myc}
\makeatletter
\def\myrow{}
\CT@everycr{\noalign{%
\global\let\CT@row@color\relax
\stepcounter{myc}%
\ifnum\value{myc}=4
  \gdef\myrow{\rowcolor{green}}
\else\ifnum\value{myc}=7
  \gdef\myrow{\rowcolor{blue}}
\else\ifnum\value{myc}=13
  \gdef\myrow{}
\else\ifnum\value{myc}=20
  \setcounter{myc}{0}
\fi\fi\fi\fi
}\myrow}



\begin{document}
\small

\begin{tabular}{>{[\themyc]}ll}
a&a\\a&a\\a&a\\a&a\\a&a\\a&a\\a&a\\a&a\\
a&a\\a&a\\a&a\\a&a\\a&a\\a&a\\a&a\\a&a\\
a&a\\a&a\\a&a\\a&a\\a&a\\a&a\\a&a\\a&a\\
a&a\\a&a\\a&a\\a&a\\a&a\\a&a\\a&a\\a&a\\
a&a\\a&a\\a&a\\a&a\\a&a\\a&a\\a&a\\a&a\\
\end{tabular}
\end{document}
Related Question