Wednesday, July 6, 2011

Beautiful tables in LaTeX

It has been quite a while since I started using LaTeX. I must say, I am in love with the way it typesets the pages. I have pretty much given up using any WYSIWYG word processors :)

There are a few nitpicks that beginners face using LaTeX. Typesetting tables is one of them. If you think you can relate to this, read on...

So here you are writing a nice report of your project work. You have some tabular data, the easiest way to represent it, is in rows and columns, (quite obviously).
You bet on a rectangular grid, nice and easy...
Here is what you get:


The LaTeX listing would be:

\begin{table}[htbp]
\caption{Table 1}
\begin{center}
\begin{tabular}{|c|c|c|c|c|}
\hline
\textbf{Heading 1} & \textbf{Heading 2} & \multicolumn{ 3}{c|}{\textbf{Heading 3}} \\ \hline
 &  & Heading 3.1 & Heading 3.2 & Heading 3.3 \\ \hline
 &  &  &  &  \\ \hline
One & One & 1 & 2 & 3 \\ \hline
Two & One & 2 & 3 & 4 \\ \hline
Three & Two & 3 & 4 & 5 \\ \hline
\end{tabular}
\end{center}
\end{table}

And then, there is your guide, who wants your tables to look gorgeous! What would you do? Curse your guide of-course! And rake your brain.
Fear not :) here is booktabs.

Booktabs provides an elegant look to the tables. It is quite flexible too. 

Consider the same example as above. I used booktabs to typeset the same, here is what I get:


Now that is some elegance :)

Here is the LaTeX listing for the same :

\begin{table}
\begin{tabular}{ccccc}
\toprule
{Heading 1} & {Heading 2} & \multicolumn{3}{c}{Heading 3} \\
\cmidrule{3-5}
{} & {} & {Heading 3.1} & {Heading 3.3} & {Heading 3.3} \\
\midrule
One & One & 1 & 2 & 3 \\
Two & One & 2 & 3 & 4 \\
Three & Two & 3 & 4 & 5 \\
\bottomrule
\end{tabular}
\end{table}

The next thing about tables is when you reference them in the text. The reference numbers may get mixed up if you are not careful.
The trick is to include the label to the table after the caption in the LaTeX source.
Here is an example LaTeX listing:

\begin{table}
\begin{tabular}{ccccc}
\toprule
{Heading 1} & {Heading 2} & \multicolumn{3}{c}{Heading 3} \\
\cmidrule{3-5}
{} & {} & {Heading 3.1} & {Heading 3.3} & {Heading 3.3} \\
\midrule
One & One & 1 & 2 & 3 \\
Two & One & 2 & 3 & 4 \\
Three & Two & 3 & 4 & 5 \\
\bottomrule
\end{tabular} 
\caption{Table 2}
\label{table2}
\end{table}

That's all for now! Enjoy TeX-ing.
Gotta get back to complete my report :)