LaTeX/Tables

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: and. To typeset material in rows and columns, the environment is needed; the optional  environment is a container for floating material similar to, into which a  environment may be included.

The 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 and  commands can be used in the same way as for pictures. For more information about the environment, see the Floating with table section.

In any case, the actual content of the table is contained within the environment.

The tabular environment
The 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:

The 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 has been loaded):

By default, if the text in a column is too wide for the page, LaTeX won’t automatically wrap it. Using 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. You can find a list in chapter Lengths.

The optional 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:

To specify a font format (such as bold, italic, etc.) for an entire column, you can add before you declare the alignment. For example 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:

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.

Expanding upon that by including some vertical lines:

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

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):

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 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, use the attribute to have the lines aligned toward the middle of the box or the  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:

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 specifier, but rather specify the line breaks by hand. In this case it is easiest to use a :

Here the argument controls the placement of the text inside the box. Other allowed values are for center and  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:. The default value is 6pt.

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

Space between rows
Re-define the command to set the space between rows:

Default value is 1.0.

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

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

Other environments inside tables
If you use some LaTeX environments inside table cells, like or :

you might encounter errors similar to ! LaTeX Error: Something's wrong--perhaps a missing \item.

To solve this problem, change column specifier to "paragraph" (, or ).

Defining multiple columns
It is possible to define many identically aligned columns at once using the 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:

Column specification using >{\cmd} and <{\cmd}
The column specification can be altered using the package. This is done in the argument of the tabular environment using for commands executed right before each column element and for commands to be executed right after each column element. As an example: to get a column in math mode enter:. Another example is changing the font: to print the column in a small font.

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

{{LaTeX/Usage|code= >{\begin{lrbox}{\boxname} }% l% <{\end{lrbox}% \underline{\unhbox\boxname} }% } }}

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

This same trick done with instead of  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 and  :

Note the use of instead of  to avoid a  error.

@ and ! expressions
The column separator can be specified with the or  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 command kills the inter-column space and replaces it with whatever is between the curly braces. To keep the initial space, use. To add space, use.

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:

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:

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 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 is as follows.

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 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

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.

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

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:. is the number of subsequent columns to merge; is either, , , or to have text wrapping specify a width. And is simply the actual data you want to be contained within that cell. A simple example:

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

The main thing to note when using 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 $$n-1$$ ampersands in each row (unless 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:

The command is just used to draw vertical borders both on the left and on the right of the cell. Even when combined with, it still draws vertical borders that only span the first row. To compensate for that, we add in the following rows spanned by the multirow. Note that we cannot just use 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 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:

Resize tables
The packages features the command  which can be used with  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.

Resizing table including the caption

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

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

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

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 before.

Alternate row colors in tables
The package provides the necessary commands to produce tables with alternate row colors, when loaded with the  option. The command has to be specified right before the  environment starts.

The command is available to deactivate highlighting from a specified row until the end of the table. Highlighting can be reactivated within the table via the 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.

or

Colors of individual cells
As above this uses the package.

Width and stretching
We keep providing documentation for and.

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.

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.

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

The tabularx package
This package provides a table environment called, which is similar to the environment except that it has a new column specifier  (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.

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

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

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

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:

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 allowing width of columns set for equal heights. allows easy and convenient writing of well balanced tables.

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

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

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

The second parameter is the column disposition. Possible values are those from the environment, plus

These are all capitals.

The tabu environment
It works pretty much like.

Note: tabu is currently broken and unmaintained

specifies the target width. The parameter can have an optional span factor.

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

The package (which is no longer maintained) provides the  environment. It has most of the features of, 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.

It uses syntax similar to, 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.

Partial vertical lines
Adding a partial vertical line to an individual cell:

Removing part of a vertical line in a particular cell:

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

Or use a parbox to center the image.

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

Footnotes in tables
The environment does not handle footnotes properly. The 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 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 for the uppermost rule (or line),  for the rules appearing in the middle of the table (such as under the header), and  for the lowermost rule. This ensures that the rule weight and spacing are acceptable. In addition, 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  or, and the third example requires  in the preamble).

Using
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 uses the  package.

Sideways tables
Tables can also be put on their side within a document using the or the  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 statement can be added besides the normal. Example:

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 package provides the command  which is like  but instead of a  argument, it takes a tag. During compilation it bookkeeps which with a certain tag contains the widest text and can stretch all es with the same tag to that width. Combined with the package, one can define a column specifier that justifies the text in all lines:comand

See the documentation of the 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 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 environment around the  environment, which is able to float and add a label and caption.

The environment initiates a type of float just as the 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:
 * is for the content itself (columns, lines, etc.).
 * is for the location of the table on the document, plus caption and label support.

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

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

The captions now show up in the list of tables, if displayed.

You can set the optional 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.

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 environment.

Centering the table horizontally works like everything else, using the command just after opening the  environment, or by enclosing it with a  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:
 * calc2latex: for LibreOffice and OpenOffice.org Calc spreadsheets,
 * excel2latex: for Microsoft Office Excel,
 * matrix2latex: for Python and MATLAB,
 * pandas: pandas DataFrame's have a method to convert data they contain to latex,
 * latex-tools: a Ruby library,
 * xtable: a library for R,
 * org-mode: for Emacs users, org-mode tables can be used inline in LaTeX documents, see for a tutorial.
 * Emacs align commands: the align commands can clean up a messy LaTeX table.
 * Online Table generator for LATeX: An online tool for creating simple tables within the browser. LaTeX format is directly generated as you type.
 * Create LaTeX tables online: Online tool.

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 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
 * <tt>ctable</tt>: allows for footnotes under table and properly spaced caption above (incorporates booktabs package)
 * <tt>slashbox</tt>: create 2D tables with the first cell containing a description for both axes. Not available in Tex Live 2011 or later.
 * <tt>diagbox</tt>: compatible to <tt>slashbox</tt>, come with Tex Live 2011 or later
 * <tt>dcolumn</tt>: decimal point alignment of numeric cells
 * <tt>rccol</tt>: advanced decimal point alignment of numeric cells with rounding
 * <tt>numprint</tt>: 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
 * <tt>spreadtab</tt>: spread sheets allowing the use of formulae
 * <tt>siunitx</tt>: alignment of tabular entries
 * <tt>pgfplotstable</tt>: 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.