texblog

Coloring every alternate table row

In one of my previous posts I describe how to color or shade every other row in a LaTeX table. However, there is a much nicer, cleaner and simpler way to color every odd/even row, making tables much more readable.

First load the xcolor package in the preamble:

\usepackage[table]{xcolor}

and define any color you like, e.g. light gray:

\definecolor{lightgray}{gray}{0.9}

Set the row color(s) just before opening the tabular environment for even and odd rows:

\rowcolors{<starting row index>}{<odd row color>}{<even row color>}

To use only one color, leave either of the row color arguments blank.

Complete code example:

\documentclass[11pt]{article}
\usepackage[table]{xcolor}
\definecolor{lightgray}{gray}{0.9}
\begin{document}
\begin{table}[ht]
\caption{default}
\begin{center}
\rowcolors{1}{}{lightgray}
\begin{tabular}{r|rrrrr}
  \hline
 & 1 & 2 & 3 & 4 & 5 \\
  \hline
1 & 2.36 & 1.08 & -0.49 & -0.82 & -0.65 \\
  2 & -0.68 & -1.13 & -0.42 & -0.72 & 1.51 \\
  3 & -1.00 & 0.02 & -0.54 & 0.31 & 1.28 \\
  4 & -0.99 & -0.54 & 0.97 & -1.12 & 0.59 \\
  5 & -2.35 & -0.29 & -0.53 & 0.30 & -0.30 \\
  6 & -0.10 & 0.06 & -0.85 & 0.10 & -0.60 \\
  7 & 1.28 & -0.46 & 1.33 & -0.66 & -1.80 \\
  8 & 0.80 & 0.46 & 1.37 & 1.73 & 1.93 \\
  9 & -0.75 & 0.28 & 0.51 & 0.19 & 0.58 \\
  10 & -1.64 & -0.12 & -1.17 & -0.10 & -0.04 \\
   \hline
\end{tabular}
\end{center}
\end{table}
\end{document}

Nope, the code box above was colored in a different way :-).

And here is the result:

Table row shading example

If you like the way Apple colors/colored tables, try using light blue:

\definecolor{lightblue}{rgb}{0.93,0.95,1.0}

I used R to generate the table:

library(xtable)
xtable(replicate(5, rnorm(10)))

Thanks to TJ Ellis for his comment.

 
Addendum:
Use the following code in your preamble to achieve the same effect automatically throughout the document. It redefines the tabular environment by adding the rowcolors command before \begin{tabular}.

\usepackage[table]{xcolor}
\definecolor{lightgray}{gray}{0.9}
\let\oldtabular\tabular
\let\endoldtabular\endtabular
\renewenvironment{tabular}{\rowcolors{2}{white}{lightgray}\oldtabular}{\endoldtabular}
Exit mobile version