LaTeX/Tables

From testwiki
Revision as of 21:02, 24 November 2024 by 134.2.163.206 (talk) (Using booktabs: fix booktabs example)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Template:LaTeX/Top


Tables are a common feature in academic writing, often used to summarize research results. Mastering the art of table construction in LaTeX is therefore necessary to produce quality papers and with sufficient practice one can print beautiful tables of any kind.

Keeping in mind that LaTeX is not a spreadsheet, it makes sense to use a dedicated tool to build tables and then to export these tables into the document. Basic tables are not too taxing, but anything more advanced can take a fair bit of construction; in these cases, more advanced packages can be very useful. However, first it is important to know the basics. Once you are comfortable with basic LaTeX tables, you might have a look at more advanced packages or the export options of your favorite spreadsheet. Thanks to the modular nature of LaTeX, the whole process can be automated in a fairly comfortable way.

Introduction

LaTeX has built-in support to typeset tables and provides two environments: Template:LaTeX/Environment and Template:LaTeX/Environment. To typeset material in rows and columns, the Template:LaTeX/Environment environment is needed; the optional Template:LaTeX/Environment environment is a container for floating material similar to Template:LaTeX/Environment, into which a Template:LaTeX/Environment environment may be included.

The Template:LaTeX/Environment environment contains the caption and defines the float for the table, i.e., where in the document the table should be positioned and whether we want it to be displayed centered. The Template:LaTeX/Inline and Template:LaTeX/Inline commands can be used in the same way as for pictures. For more information about the Template:LaTeX/Environment environment, see the Floating with table section.

In any case, the actual content of the table is contained within the Template:LaTeX/Environment environment.

The tabular environment

The Template:LaTeX/Environment environment can be used to typeset tables with optional horizontal and vertical lines. LaTeX determines the width of the columns automatically.

The first line of the environment has the form: Template:LaTeX/Usage

The Template:LaTeX/Parameter argument tells LaTeX the alignment to be used in each column and the vertical lines to insert.

The number of columns does not need to be specified as it is inferred by looking at the number of arguments provided. It is also possible to add vertical lines between the columns here. The following symbols are available to describe the table columns (some of them require that the package Template:LaTeX/Package has been loaded):

Template:LaTeX/Parameter left-justified column
Template:LaTeX/Parameter centered column
Template:LaTeX/Parameter right-justified column
Template:LaTeX/Parameter paragraph column with text vertically aligned at the top
Template:LaTeX/Parameter paragraph column with text vertically aligned in the middle (requires array package)
Template:LaTeX/Parameter paragraph column with text vertically aligned at the bottom (requires array package)
| vertical line
|| double vertical line

By default, if the text in a column is too wide for the page, LaTeX won’t automatically wrap it. Using Template:LaTeX/Parameter you can define a special type of column which will wrap-around the text as in a normal paragraph. You can pass the width using any unit supported by LaTeX, such as 'pt' and 'cm', or command lengths, such as Template:LaTeX/LaTeX. You can find a list in chapter Lengths.

The optional parameter Template:LaTeX/Parameter can be used to specify the vertical position of the table relative to the baseline of the surrounding text. In most cases, you will not need this option. It becomes relevant only if your table is not in a paragraph of its own. You can use the following letters:

Template:LaTeX/Parameter bottom
Template:LaTeX/Parameter center (default)
Template:LaTeX/Parameter top

To specify a font format (such as bold, italic, etc.) for an entire column, you can add Template:LaTeX/LaTeX before you declare the alignment. For example Template:LaTeX/LaTeX will indicate a three column table with the first one aligned to the left and in bold font, the second one aligned in the center and with normal font, and the third aligned to the right and in italic. The "array" package needs to be activated in the preamble for this to work.

In the first line you have pointed out how many columns you want, their alignment and the vertical lines to separate them. Once in the environment, you have to introduce the text you want, separating between cells and introducing new lines. The commands you have to use are the following:

Template:LaTeX/LaTeX column separator
Template:LaTeX/LaTeX start new row (additional space may be specified after Template:LaTeX/LaTeX using square brackets, such as Template:LaTeX/Parameter)
Template:LaTeX/LaTeX horizontal line
Template:LaTeX/LaTeX start a new line within a cell (in a paragraph column)
Template:LaTeX/LaTeX partial horizontal line beginning in column i and ending in column j

Note, any white space inserted between these commands is purely down to one's preferences. I personally add spaces between to make it easier to read.

Basic examples

This example shows how to create a simple table in LaTeX. It is a three-by-three table, but without any lines.

\begin{tabular}{ l c r }
  1 & 2 & 3 \\
  4 & 5 & 6 \\
  7 & 8 & 9 \\
\end{tabular}

123456789

Template:BookCat

Expanding upon that by including some vertical lines:

\begin{tabular}{ l | c | r }
  1 & 2 & 3 \\
  4 & 5 & 6 \\
  7 & 8 & 9 \\
\end{tabular}

123456789

Template:BookCat

To add horizontal lines to the very top and bottom edges of the table:

\begin{tabular}{ l | c | r }
  \hline			
  1 & 2 & 3 \\
  4 & 5 & 6 \\
  7 & 8 & 9 \\
  \hline  
\end{tabular}

123456789

Template:BookCat

And finally, to add lines between all rows, as well as centering (notice the use of the center environment - of course, the result of this is not obvious from the preview on this web page):

\begin{center}
  \begin{tabular}{ l | c | r }
    \hline
    1 & 2 & 3 \\ \hline
    4 & 5 & 6 \\ \hline
    7 & 8 & 9 \\
    \hline
  \end{tabular}
\end{center}

123456789

Template:BookCat

\begin{center}
  \begin{tabular}{ | l | c | r }
    \hline
    1 & 2 & 3 \\ \hline
    4 & 5 & 6 \\ \hline
    7 & 8 & 9 \\
    \hline
  \end{tabular}
\end{center}

123456HLINE TBD789

Template:BookCat

\begin{tabular}{|r|l|}
  \hline
  7C0 & hexadecimal \\
  3700 & octal \\ \cline{2-2}
  11111000000 & binary \\
  \hline \hline
  1984 & decimal \\
  \hline
\end{tabular}

Template:BookCat

Text wrapping in tables

LaTeX's algorithms for formatting tables have a few shortcomings. One is that it will not automatically wrap text in cells, even if it overruns the width of the page. For columns that will contain text whose length exceeds the column's desired width, it is recommended that you use the Template:LaTeX/Parameter attribute and specify the desired width of the column (although it may take some trial-and-error to get the result you want). For a more convenient method, have a look at The tabularx package, or The tabulary package.

Instead of Template:LaTeX/Parameter, use the Template:LaTeX/Parameter attribute to have the lines aligned toward the middle of the box or the Template:LaTeX/Parameter attribute to align along the bottom of the box.

Here is a simple example. The following code creates two tables with the same code; the only difference is that the last column of the second one has a defined width of 5 centimeters, while in the first one we didn't specify any width. Compiling this code:

Template:LaTeX/Usage

You get the following output:

Note that the first table has been cropped, since the output is wider than the page width.

Manually broken paragraphs in table cells

Sometimes it is necessary to not rely on the breaking algorithm when using the Template:LaTeX/Parameter specifier, but rather specify the line breaks by hand. In this case it is easiest to use a Template:LaTeX/LaTeX:

Template:LaTeX/Usage

Here the Template:LaTeX/Parameter argument controls the placement of the text inside the box. Other allowed values are Template:LaTeX/Parameter for center and Template:LaTeX/Parameter for bottom.

Space between columns

To tweak the space between columns (LaTeX will by default choose very tight columns), one can alter the column separation: Template:LaTeX/LaTeX. The default value is 6pt.

One can also introduce a horizontal space with hspace like this: Template:LaTeX/LaTeX There are different options for the hspace length.

Space between rows

Re-define the Template:LaTeX/LaTeX command to set the space between rows: Template:LaTeX/Usage Default value is 1.0.

An alternative way to adjust the rule spacing is to add Template:LaTeX/LaTeX before or after the Template:LaTeX/LaTeX and Template:LaTeX/LaTeX commands:

Template:LaTeX/Usage

You may also specify the skip after a line explicitly using glue after the line terminator

Template:LaTeX/Usage

Other environments inside tables

If you use some LaTeX environments inside table cells, like Template:LaTeX/Environment or Template:LaTeX/Environment:

Template:LaTeX/Usage

you might encounter errors similar to

! LaTeX Error: Something's wrong--perhaps a missing \item.

To solve this problem, change column specifier to "paragraph" (Template:LaTeX/Parameter, Template:LaTeX/Parameter or Template:LaTeX/Parameter).

Template:LaTeX/Usage

Defining multiple columns

It is possible to define many identically aligned columns at once using the Template:LaTeX/LaTeX syntax. This is particularly useful when your table has many columns.

Here is a table with six centered columns flanked by a single column on each side:

\begin{tabular}{l*{6}{c}r}
Team              & P & W & D & L & F  & A & Pts \\
\hline
Manchester United & 6 & 4 & 0 & 2 & 10 & 5 & 12  \\
Celtic            & 6 & 3 & 0 & 3 &  8 & 9 &  9  \\
Benfica           & 6 & 2 & 1 & 3 &  7 & 8 &  7  \\
FC Copenhagen     & 6 & 2 & 1 & 3 &  5 & 8 &  7  \\
\end{tabular}

Template:BookCat

Column specification using >{\cmd} and <{\cmd}

The column specification can be altered using the Template:LaTeX/Package package. This is done in the argument of the tabular environment using Template:LaTeX/LaTeX for commands executed right before each column element and Template:LaTeX/LaTeX for commands to be executed right after each column element. As an example: to get a column in math mode enter: Template:LaTeX/LaTeX. Another example is changing the font: Template:LaTeX/LaTeX to print the column in a small font.

The argument of the Template:LaTeX/LaTeX and Template:LaTeX/LaTeX specifications must be correctly balanced when it comes to Template:LaTeX/LaTeX and Template:LaTeX/LaTeX characters. This means that Template:LaTeX/LaTeX is valid, while Template:LaTeX/LaTeX will not work and Template:LaTeX/LaTeX is not valid. If there is the need to use the text of the table as an argument (for instance, using the Template:LaTeX/LaTeX to produce bold text), one should use the Template:LaTeX/LaTeX and Template:LaTeX/LaTeX commands: Template:LaTeX/LaTeX produces the intended effect. This works only for some basic LaTeX commands. For other commands, such as Template:LaTeX/LaTeX to underline text, it is necessary to temporarily store the column text in a box using Template:LaTeX/LaTeX. First, you must define such a box with Template:LaTeX/LaTeX and then you can define:

Template:LaTeX/Usage

This stores the text in a box and afterwards, takes the text out of the box with Template:LaTeX/LaTeX (this destroys the box, if the box is needed again one should use Template:LaTeX/LaTeX instead) and passing it to Template:LaTeX/LaTeX. (For LaTeX2e, you may want to use Template:LaTeX/LaTeX instead of Template:LaTeX/LaTeX.)

This same trick done with Template:LaTeX/LaTeX instead of Template:LaTeX/LaTeX can force all lines in a table to have equal height, instead of the natural varying height that can occur when e.g. math terms or superscripts occur in the text.

Here is an example showing the use of both Template:LaTeX/LaTeX and Template:LaTeX/LaTeX :

Template:LaTeX/Usage

Note the use of Template:LaTeX/LaTeX instead of Template:LaTeX/LaTeX to avoid a Template:LaTeX/LaTeX error.

@ and ! expressions

The column separator can be specified with the Template:LaTeX/LaTeX or Template:LaTeX/LaTeX constructs.

It typically takes some text as its argument, and when appended to a column, it will automatically insert that text into each cell in that column before the actual data for that cell. The Template:LaTeX/LaTeX command kills the inter-column space and replaces it with whatever is between the curly braces. To keep the initial space, use Template:LaTeX/LaTeX. To add space, use Template:LaTeX/LaTeX.

Admittedly, this is not that clear, and so will require a few examples to clarify. Sometimes, it is desirable in scientific tables to have the numbers aligned on the decimal point. This can be achieved by doing the following:

\begin{tabular}{r@{.}l}
  3   & 14159 \\
  16  & 2     \\
  123 & 456   \\
\end{tabular}

3.1415916.2123.456

Template:BookCat

The space-suppressing qualities of the @-expression actually make it quite useful for manipulating the horizontal spacing between columns. Given a basic table, and varying the column descriptions:

Template:LaTeX/Usage

{|l|l|}

{|@{}l|l@{}|}

{|@{}l@{}|l@{}|}

{|@{}l@{}|@{}l@{}|}

Aligning columns at decimal points using dcolumn

Instead of using @-expressions to build columns of decimals aligned to the decimal point (or equivalent symbol), it is possible to center a column on the decimal separator using the Template:LaTeX/Package package, which provides a new column specifier for floating point data. See the dcolumn package documentation for more information, but a simple way to use Template:LaTeX/Package is as follows.

\usepackage{dcolumn}
\ldots
\newcolumntype{d}[1]{D{.}{\cdot}{#1} }
%the argument for d specifies the maximum number of decimal places
\begin{tabular}{l r c d{1} }
Left&Right&Center&\mathrm{Decimal}\\
1&2&3&4\\
11&22&33&44\\
1.1&2.2&3.3&4.4\\
\end{tabular}

Template:BookCat

A negative argument provided for the number of decimal places in the new column type allows unlimited decimal places, but may result in rather wide columns. Rounding is not applied, so the data to be tabulated should be adjusted to the number of decimal places specified. Note that a decimal aligned column is typeset in math mode, hence the use of \mathrm for the column heading in the example above. Also, text in a decimal aligned column (for example the header) will be right-aligned before the decimal separator (assuming there's no decimal separator in the text). While this may be fine for very short text, or numeric column headings, it looks cumbersome in the example above. A solution to this is to use the Template:LaTeX/LaTeX command described below, specifying a single column and its alignment. For example to center the header Decimal over its column in the above example, the first line of the table itself would be Template:LaTeX/LaTeX

Bold text and dcolumn

To draw attention to particular entries in a table, it may be nice to use bold text. Ordinarily this is easy, but as dcolumn needs to see the decimal point it is rather harder to do. In addition, the usual bold characters are wider than their normal counterparts, meaning that although the decimals may align nicely, the figures (for more than 2--3 digits on one side of the decimal point) will be visibly misaligned. It is however possible to use normal width bold characters and define a new bold column type, as shown below.[1]

\usepackage{dcolumn}
%here we're setting up a version of the math fonts with normal x-width
\DeclareMathVersion{nxbold} 
\SetSymbolFont{operators}{nxbold}{OT1}{cmr} {b}{n}
\SetSymbolFont{letters}  {nxbold}{OML}{cmm} {b}{it}
\SetSymbolFont{symbols}  {nxbold}{OMS}{cmsy}{b}{n}

\begin{document}
\makeatletter
\newcolumntype{d}{D{.}{.}{-1} } %decimal column as before
%wide bold decimal column
\newcolumntype{B}[3]{>{\boldmath\DC@{#1}{#2}{#3} }c<{\DC@end} } 
%normal width bold decimal column
\newcolumntype{Z}[3]{>{\mathversion{nxbold}\DC@{#1}{#2}{#3} }c<{\DC@end} } 
\makeatother
\begin{tabular}{l l d}
    Type &M & \multicolumn{1}{c}{N} \\
    Normal & 1 & 22222.222 \\
    Bold (standard)&10 & \multicolumn{1}{B{.}{.}{-1} }{22222.222}\\
    Bold (nxbold)&100 & \multicolumn{1}{Z{.}{.}{-1} }{22222.222}\\
\end{tabular}
\end{document}

Template:BookCat

Row specification

It might be convenient to apply the same command over every cell of a row, just as for column. Unfortunately the Template:LaTeX/Environment environment cannot do that by default. We will need Template:LaTeX/Package instead, which provides the Template:LaTeX/LaTeX option.

Template:LaTeX/Usage

Spanning

To complete this tutorial, we take a quick look at how to generate slightly more complex tables. Unsurprisingly, the commands necessary have to be embedded within the table data itself.

Rows spanning multiple columns

The command for this looks like this: Template:LaTeX/LaTeX. Template:LaTeX/Parameter is the number of subsequent columns to merge; Template:LaTeX/Parameter is either Template:LaTeX/Parameter, Template:LaTeX/Parameter, Template:LaTeX/Parameter, or to have text wrapping specify a width Template:LaTeX/LaTeX . And Template:LaTeX/Parameter is simply the actual data you want to be contained within that cell. A simple example:

\begin{tabular}{ |l|l| }
  \hline
  \multicolumn{2}{|c|}{Team sheet} \\
  \hline
  GK & Paul Robinson \\
  LB & Lucas Radebe \\
  DC & Michael Duberry \\
  DC & Dominic Matteo \\
  RB & Dider Domi \\
  MC & David Batty \\
  MC & Eirik Bakke \\
  MC & Jody Morris \\
  FW & Jamie McMaster \\
  ST & Alan Smith \\
  ST & Mark Viduka \\
  \hline
\end{tabular}

Template:BookCat

Columns spanning multiple rows

The first thing you need to do is add Template:LaTeX/LaTeX to the preamble[2]. This then provides the command needed for spanning rows: Template:LaTeX/LaTeX. The arguments are pretty simple to deduce (Template:LaTeX/LaTeX for the width means the content's natural width).

...
\usepackage{multirow}
...

\begin{tabular}{ |l|l|l| }
\hline
\multicolumn{3}{ |c| }{Team sheet} \\
\hline
Goalkeeper & GK & Paul Robinson \\ \hline
\multirow{4}{*}{Defenders} & LB & Lucas Radebe \\
 & DC & Michael Duburry \\
 & DC & Dominic Matteo \\
 & RB & Didier Domi \\ \hline
\multirow{3}{*}{Midfielders} & MC & David Batty \\
 & MC & Eirik Bakke \\
 & MC & Jody Morris \\ \hline
Forward & FW & Jamie McMaster \\ \hline
\multirow{2}{*}{Strikers} & ST & Alan Smith \\
 & ST & Mark Viduka \\
\hline
\end{tabular}

Template:BookCat

The main thing to note when using Template:LaTeX/LaTeX is that a blank entry must be inserted for each appropriate cell in each subsequent row to be spanned.

If there is no data for a cell, just don't type anything, but you still need the "&" separating it from the next column's data. The astute reader will already have deduced that for a table of n columns, there must always be n1 ampersands in each row (unless Template:LaTeX/LaTeX is also used).

Spanning in both directions simultaneously

Here is a nontrivial example of how to use spanning in both directions simultaneously and have the borders of the cells drawn correctly:

\usepackage{multirow}

\begin{tabular}{cc|c|c|c|c|l}
\cline{3-6}
& & \multicolumn{4}{ c| }{Primes} \\ \cline{3-6}
& & 2 & 3 & 5 & 7 \\ \cline{1-6}
\multicolumn{1}{ |c  }{\multirow{2}{*}{Powers} } &
\multicolumn{1}{ |c| }{504} & 3 & 2 & 0 & 1 &     \\ \cline{2-6}
\multicolumn{1}{ |c  }{}                        &
\multicolumn{1}{ |c| }{540} & 2 & 3 & 1 & 0 &     \\ \cline{1-6}
\multicolumn{1}{ |c  }{\multirow{2}{*}{Powers} } &
\multicolumn{1}{ |c| }{gcd} & 2 & 2 & 0 & 0 & min \\ \cline{2-6}
\multicolumn{1}{ |c  }{}                        &
\multicolumn{1}{ |c| }{lcm} & 3 & 3 & 1 & 1 & max \\ \cline{1-6}
\end{tabular}

Template:BookCat

The command Template:LaTeX/LaTeX is just used to draw vertical borders both on the left and on the right of the cell. Even when combined with Template:LaTeX/LaTeX, it still draws vertical borders that only span the first row. To compensate for that, we add Template:LaTeX/LaTeX in the following rows spanned by the multirow. Note that we cannot just use Template:LaTeX/LaTeX to draw horizontal lines, since we do not want the line to be drawn over the text that spans several rows. Instead we use the command Template:LaTeX/LaTeX and opt out the first column that contains the text "Powers".

Here is another example exploiting the same ideas to make the familiar and popular "2x2" or double dichotomy:

\begin{tabular}{ r|c|c| }
\multicolumn{1}{r}{}
 &  \multicolumn{1}{c}{noninteractive}
 & \multicolumn{1}{c}{interactive} \\
\cline{2-3}
massively multiple & Library & University \\
\cline{2-3}
one-to-one & Book & Tutor \\
\cline{2-3}
\end{tabular}

Template:BookCat

Controlling table size

Resize tables

The Template:LaTeX/Package packages features the command Template:LaTeX/LaTeX which can be used with Template:LaTeX/Environment to specify the height and width of a table. The following example shows how to resize a table to 8cm width while maintaining the original width/height ratio.

Template:LaTeX/Usage

Resizing table including the caption

Template:LaTeX/Usage

Alternatively you can use Template:LaTeX/LaTeX in the same way but with ratios rather than fixed sizes:

Template:LaTeX/Usage

Changing font size

A table can be globally switched to a different font size by simply adding the desired size command (here: Template:LaTeX/LaTeX) in the table scope, which may be after the Template:LaTeX/LaTeX statement if you use floats, otherwise you need to add a group delimiter.

Template:LaTeX/Usage

Template:LaTeX/Usage

Alternatively, you can change the default font for all the tables in your document by placing the following code in the preamble:

Template:LaTeX/Usage

See Fonts for named font sizes. The table caption font size is not affected. To control the caption font size, see Caption Styles.

It is also possible to change the vertical space between rows using Template:LaTeX/LaTeX before Template:LaTeX/LaTeX.

Colors

Alternate row colors in tables

The Template:LaTeX/Package package provides the necessary commands to produce tables with alternate row colors, when loaded with the Template:LaTeX/Parameter option. The command Template:LaTeX/LaTeX has to be specified right before the Template:LaTeX/Environment environment starts.

\documentclass{article}

\usepackage[table]{xcolor}

\begin{document}

\begin{center}
\rowcolors{1}{green}{pink}

\begin{tabular}{lll}
odd 	& odd 	& odd \\
even 	& even 	& even\\
odd 	& odd 	& odd \\
even 	& even 	& even\\
\end{tabular}
\end{center}

\end{document}

Template:BookCat

The command Template:LaTeX/LaTeX is available to deactivate highlighting from a specified row until the end of the table. Highlighting can be reactivated within the table via the Template:LaTeX/LaTeX command. If while using these commands you experience "misplaced \noalign errors" then use the commands at the very beginning or end of a row in your tabular. Template:LaTeX/Usage or Template:LaTeX/Usage

Colors of individual cells

As above this uses the Template:LaTeX/Package package.

Template:LaTeX/Usage

Width and stretching

We keep providing documentation for Template:LaTeX/Environment and Template:LaTeX/Environment.

The tabular* environment

This is basically a slight extension on the original tabular version, although it requires an extra argument (before the column descriptions) to specify the preferred width of the table.

\begin{tabular*}{0.75\textwidth}{ | c | c | c | r | }
  \hline
  label 1 & label 2 & label 3 & label 4 \\
  \hline 
  item 1  & item 2  & item 3  & item 4  \\
  \hline
\end{tabular*}

Template:BookCat

However, that may not look quite as intended. The columns are still at their natural width (just wide enough to fit their contents) while the rows are as wide as the table width specified. If you do not like this default, you must also explicitly insert extra column space. LaTeX has rubber lengths, which, unlike others, are not fixed. LaTeX can dynamically decide how long the lengths should be. So, an example of this is the following.

\begin{tabular*}{0.75\textwidth}{@{\extracolsep{\fill} } | c | c | c | r | }
  \hline
  label 1 & label 2 & label 3 & label 4 \\
  \hline 
  item 1  & item 2  & item 3  & item 4  \\
  \hline
\end{tabular*}

Template:BookCat

You will notice the Template:LaTeX/LaTeX construct added at the beginning of the column description. Within it is the Template:LaTeX/LaTeX command, which requires a width. A fixed width could have been used. However, by using a rubber length, such as Template:LaTeX/LaTeX, the columns are automatically spaced evenly.

The tabularx package

This package provides a table environment called Template:LaTeX/Environment, which is similar to the Template:LaTeX/Environment environment except that it has a new column specifier Template:LaTeX/Parameter (in uppercase). The column(s) specified with this specifier will be stretched to make the table as wide as specified, greatly simplifying the creation of tables.

\usepackage{tabularx}
% ...

\begin{tabularx}{\textwidth}{ |X|X|X|X| }
  \hline
  label 1 & label 2 & label 3 & label 4 \\
  \hline 
  item 1  & item 2  & item 3  & item 4  \\
  \hline
\end{tabularx}

Template:BookCat

The content provided for the boxes is treated as for a Template:LaTeX/Parameter column, except that the width is calculated automatically. If you use the package Template:LaTeX/Package, you may also apply any Template:LaTeX/LaTeX or Template:LaTeX/LaTeX command to achieve specific behavior (like Template:LaTeX/LaTeX, or Template:LaTeX/LaTeX) as described previously.

Another option is to use Template:LaTeX/LaTeX to format selected columns in a different way. It defines a new column specifier, e.g. Template:LaTeX/Parameter (in uppercase). In this example, the second and fourth column is adjusted in a different way (Template:LaTeX/LaTeX):

\usepackage{tabularx}
% ...

\newcolumntype{R}{>{\raggedleft\arraybackslash}X}%
\begin{tabularx}{\textwidth}{ |l|R|l|R| }
  \hline
  label 1 & label 2 & label 3 & label 4 \\
  \hline 
  item 1  & item 2  & item 3  & item 4  \\
  \hline
\end{tabularx}

Template:BookCat

Tabularx with rows spanning multiple columns using Template:LaTeX/LaTeX. The two central columns are posing as one by using the Template:LaTeX/Parameter option. Note that the Template:LaTeX/LaTeX width (which in this example is 2) should equal the (in this example 1+1) width of the spanned columns:

\usepackage{tabularx}
% ...

\begin{tabularx}{1\textwidth}{ |>{\setlength\hsize{1\hsize}\centering}X|>{\setlength\hsize{1\hsize}\raggedleft}X@{} >{\setlength\hsize{1\hsize}\raggedright}X|>{\setlength\hsize{1\hsize}\centering}X| } 
  \hline
Label 1 & \multicolumn{2}{>{\centering\setlength\hsize{2\hsize} }X|}{Label 2} & Label 3\tabularnewline
\hline 
  123  & 123  & 456  & 123  \tabularnewline
  \hline
  123  & 123  & 456  & 123  \tabularnewline
  \hline
\end{tabularx}

Template:BookCat

In a way analogous to how new commands with arguments can be created with \newcommand, new column types with arguments can be created with \newcolumntype as follows:

Template:LaTeX/Usage

where since there are 4 columns, the sum of the \hsize's (1 + 0.5 + 0.5 + 2) must be equal to 4. The default value used by tabularx for \hsize is 1.

The tabulary package

tabulary is a modified Template:LaTeX/Package allowing width of columns set for equal heights. Template:LaTeX/Package allows easy and convenient writing of well balanced tables.

The problem with Template:LaTeX/Package is that it leaves much blank if your cells are almost empty. Besides, it is not easy to have different column sizes.

Template:LaTeX/Package tries to balance the column widths so that each column has at least its natural width, without exceeding the maximum length.

Template:LaTeX/Usage

The first parameter is the maximum width. Template:LaTeX/Package will try not to exceed it, but it will not stretch to it if there is not enough content, contrary to Template:LaTeX/Package.

The second parameter is the column disposition. Possible values are those from the Template:LaTeX/Environment environment, plus

Template:LaTeX/Parameter left-justified balanced column
Template:LaTeX/Parameter centered balanced column
Template:LaTeX/Parameter right-justified balanced column
Template:LaTeX/Parameter left-right-justified balanced column

These are all capitals.

The tabu environment

It works pretty much like Template:LaTeX/Environment.

Note: tabu is currently broken and unmaintained

Template:LaTeX/Usage

Template:LaTeX/LaTeX specifies the target width. The Template:LaTeX/Parameter parameter can have an optional span factor.

Table across several pages

Long tables are natively supported by LaTeX thanks to the Template:LaTeX/Environment environment, which replaces both the Template:LaTeX/Environment and Template:LaTeX/Environment environments or rather combines them into a single environment. Unfortunately, this environment does not support stretching (X columns).

The Template:LaTeX/Package package (which is no longer maintained) provides the Template:LaTeX/Environment environment. It has most of the features of Template:LaTeX/Environment, with the additional capability to span multiple pages.

LaTeX can do well with long tables: you can specify a header that will repeat on every page, a header for the first page only, and the same for the footer.

Template:LaTeX/Usage

It uses syntax similar to Template:LaTeX/Environment, so you should have a look at its documentation if you want to know more.

Alternatively you can try one of the following packages supertabular or xtab, an extended and somewhat improved version of Template:LaTeX/Package.

Partial vertical lines

Adding a partial vertical line to an individual cell:

\begin{tabular}{ l c r }
  \hline
  1 & 2 & 3 \\ \hline
  4 & 5 & \multicolumn{1}{r|}{6}  \\ \hline
  7 & 8 & 9 \\ \hline
\end{tabular}

Template:BookCat

Removing part of a vertical line in a particular cell:

\begin{tabular}{ | l | c | r | }
  \hline
  1 & 2 & 3 \\ \hline
  4 & 5 & \multicolumn{1}{r}{6} \\ \hline
  7 & 8 & 9 \\ \hline
\end{tabular}

Template:BookCat

Vertically centered images

Inserting images into a table row will align it at the top of the cell. By using the Template:LaTeX/Package package this problem can be solved. Defining a new columntype will keep the image vertically centered.

Template:LaTeX/Usage

Or use a parbox to center the image.

Template:LaTeX/Usage

A raisebox works as well, also allowing to manually fine-tune the alignment with its first parameter.

Template:LaTeX/Usage

Footnotes in tables

The Template:LaTeX/Environment environment does not handle footnotes properly. The Template:LaTeX/Environment fixes that.

Professional tables

Many professionally typeset books and journals feature simple tables, which have appropriate spacing above and below lines, and almost never use vertical rules. Many examples of LaTeX tables (including this Wikibook) showcase the use of vertical rules (using "|"), and double-rules (using Template:LaTeX/LaTeX or "||"), which are regarded as unnecessary and distracting in a professionally published form. The booktabs package is useful for easily providing this professionalism in LaTeX tables, and the documentation also provides guidelines on what constitutes a "good" table.

In brief, the package uses Template:LaTeX/LaTeX for the uppermost rule (or line), Template:LaTeX/LaTeX for the rules appearing in the middle of the table (such as under the header), and Template:LaTeX/LaTeX for the lowermost rule. This ensures that the rule weight and spacing are acceptable. In addition, Template:LaTeX/LaTeX can be used for mid-rules that span specified columns. The following example contrasts the use of booktabs and two equivalent normal LaTeX implementations (the second example requires Template:LaTeX/LaTeX or Template:LaTeX/LaTeX, and the third example requires Template:LaTeX/LaTeX in the preamble).

Normal LaTeX

\begin{tabular}{lllllr}
\hline
\multicolumn{5}{c}{Item} \\
\cline{1-5}
Animal    & Description & Price (\$) \\
\hline
Gnat      & per gram    & 13.65      \\
          & each        & 0.01       \\
Gnu       & stuffed     & 92.50      \\
Emu       & stuffed     & 33.33      \\
Armadillo & frozen      & 8.99       \\
\hline
\end{tabular}

Template:BookCat

\usepackage{array} 
%or \usepackage{dcolumn}
...
\begin{tabular}{llr}
\firsthline
\multicolumn{2}{c}{Item} \\
\cline{1-2}
Animal    & Description & Price (\$) \\
\hline
Gnat      & per gram    & 13.65      \\
          & each        & 0.01       \\
Gnu       & stuffed     & 92.50      \\
Emu       & stuffed     & 33.33      \\
Armadillo & frozen      & 8.99       \\
\lasthline
\end{tabular}

Template:BookCat

\usepackage{booktabs}
\begin{tabular}{lllr}  
\toprule
\multicolumn{2}{c}{Item} \\
\cmidrule(r){1-2}
Animal    & Description & Price (\$) & 2\\
\midrule
Gnu       & stuffed     & 92.50     & 2 \\
Emu       & stuffed     & 33.33    & 2  \\
Armadillo & frozen      & 8.99     & 2  \\
\bottomrule
\end{tabular}

Template:BookCat

Usually the need arises for footnotes under a table (and not at the bottom of the page), with a caption properly spaced above the table. These are addressed by the ctable package. It provides the option of a short caption given to be inserted in the list of tables, instead of the actual caption (which may be quite long and inappropriate for the list of tables). The Template:LaTeX/Package uses the Template:LaTeX/Package package.

Sideways tables

Tables can also be put on their side within a document using the Template:LaTeX/Package or the Template:LaTeX/Package package. See the Rotations chapter.

Table with legend

To add a legend to a table the caption package can be used. With the caption package a Template:LaTeX/LaTeX statement can be added besides the normal Template:LaTeX/LaTeX. Example:

Template:LaTeX/Usage

The normal caption is needed for labels and references.

The eqparbox package

On rare occasions, it might be necessary to stretch every row in a table to the natural width of its longest line, for instance when one has the same text in two languages and wishes to present these next to each other with lines synching up. A tabular environment helps control where lines should break, but cannot justify the text, which leads to ragged right edges. The Template:LaTeX/Package package provides the command Template:LaTeX/LaTeX which is like Template:LaTeX/LaTeX but instead of a Template:LaTeX/Parameter argument, it takes a tag. During compilation it bookkeeps which Template:LaTeX/LaTeX with a certain tag contains the widest text and can stretch all Template:LaTeX/LaTeXes with the same tag to that width. Combined with the Template:LaTeX/Package package, one can define a column specifier that justifies the text in all lines:comand

Template:LaTeX/Usage

See the documentation of the Template:LaTeX/Package package for more details.

The paracol package

The various tabular environments available for LaTeX are feature rich; however, they lack the ability to automatically page break large rows. The paracol package provides automatic page breaks in between rows and in certain cases can replace the tabular environment. Such situations could be common in documents that require translations and definitions, which may also includes lists.

For further detail see the documentation of the Template:LaTeX/Package package.


Floating with table

In WYSIWYG document processors, it is common to put tables in the middle of the text. This is what we have been doing until now. Professional documents, however, often make it a point to print tables on a dedicated page so that they do not disrupt the flow. From the point of view of the source code, one has no idea on which page the current text is going to lie, so it is hardly possible to guess which page may be appropriate for our table. LaTeX can automate this task by abstracting objects such as tables, pictures, etc., and deciding for us where they might fit best. This abstraction is called a float. Generally, an object that is floated will appear in the vicinity of its introduction in the source file, but one can choose to control its position also.

To tell LaTeX we want to use our table as a float, we need to put a Template:LaTeX/Environment environment around the Template:LaTeX/Environment environment, which is able to float and add a label and caption.

Template:Warning

The Template:LaTeX/Environment environment initiates a type of float just as the environment Template:LaTeX/Environment. In fact, the two bear a lot of similarities (positioning, captions, etc.). More information about floating environments, captions etc. can be found in Floats, Figures and Captions.

The environment names may now seem quite confusing. Let's sum it up:

Template:LaTeX/Usage

In the table, we used a label, so now we can refer to it just like any other reference: Template:LaTeX/Usage

The Template:LaTeX/Environment environment is also useful when you want to have a list of tables at the beginning or end of your document with the command

Template:LaTeX/Usage The captions now show up in the list of tables, if displayed.

You can set the optional parameter Template:LaTeX/Parameter to define the position of the table, where it should be placed. The following characters are all possible placements. Using sequences of it define your "wishlist" to LaTeX.

Template:LaTeX/Parameter where the table is declared (here)
Template:LaTeX/Parameter at the top of the page
Template:LaTeX/Parameter at the bottom of the page
Template:LaTeX/Parameter on a dedicated page of floats
Template:LaTeX/Parameter override the default float restrictions. E.g., the maximum size allowed of a Template:LaTeX/Parameter float is normally quite small; if you want a large one, you need this Template:LaTeX/Parameter parameter as well.

Default is tbp, which means that it is by default placed on the top of the page. If that's not possible, it's placed at the bottom if possible, or finally with other floating environments on an extra page.

You can force LaTeX to use one given position. E.g. [!h] forces LaTeX to place it exactly where you place it (Except when it's really impossible, e.g you place a table here and this place would be the last line on a page). Again, understand it correctly: it urges LaTeX to put the table at a specific place, but it will not be placed there if LaTeX thinks it will not look great. If you really want to place your table manually, do not use the Template:LaTeX/Environment environment.

Centering the table horizontally works like everything else, using the Template:LaTeX/LaTeX command just after opening the Template:LaTeX/Environment environment, or by enclosing it with a Template:LaTeX/Environment environment.

Using spreadsheets and data analysis tools

For complex or dynamic tables, you may want to use a spreadsheet. You might save lots of time by building tables using specialized software and exporting them in LaTeX format. The following plugins and libraries are available for some popular software:

However, copying the generated source code to your document is not convenient at all. For maximum flexibility, generate the source code to a separate file which you can input from your main document file with the Template:LaTeX/LaTeX command. If your spreadsheet supports command-line, you can generate your complete document (table included) in one command, using a Makefile for example.

See Modular Documents for more details.

Need more features?

Have a look at one of the following packages:

  • hhline: do whatever you want with horizontal lines
  • array: gives you more freedom on how to define columns
  • colortbl: make your table more colorful
  • threeparttable makes it possible to put footnotes both within the table and its caption
  • arydshln: creates dashed horizontal and vertical lines
  • ctable: allows for footnotes under table and properly spaced caption above (incorporates booktabs package)
  • slashbox: create 2D tables with the first cell containing a description for both axes. Not available in Tex Live 2011 or later.
  • diagbox: compatible to slashbox, come with Tex Live 2011 or later
  • dcolumn: decimal point alignment of numeric cells
  • rccol: advanced decimal point alignment of numeric cells with rounding
  • numprint: print numbers, in the current mode (text or math) in order to use the correct font, with separators, exponent and/or rounded to a given number of digits. tabular(*), array, tabularx, and longtable environments are supported using all features of numprint
  • spreadtab: spread sheets allowing the use of formulae
  • siunitx: alignment of tabular entries
  • pgfplotstable: loads, rounds, formats and postprocesses numerical tables, e.g. by importing the data directly from .csv (comma-separated value) files instead of manually writing the whole tables in LaTeX code. Programs such as Excel, LibreOffice Calc etc. can export data sheets as .csv files.

References

Template:Reflist


Template:LaTeX/Bottom


fr:LaTeX/Faire_des_tableaux nl:LaTeX/Tabellen pl:LaTeX/Tabele

  1. Template:Cite web
  2. Package multirow on CTAN