LaTeX/表格
在學術論文的寫作中,表格是一個常見的特徵,通常用於總結研究結果。 因此,這是製作出高質量的論文需要掌握的一項技能。
但是,如果 LaTeX 有個領域是最不直觀的就是表格。 製作基本表格並不太費力,但您很快就會注意到,任何更高級的東西都可能需要相當多的構建。 所以,我們慢慢開始並從那裡建立起來。
Workaround: You might save lots of time by converting tables from OpenOffice spreadsheets with the help of open source plugins, see e.g. http://calc2latex.sourceforge.net/.
tabular 環境
[編輯]The tabular
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:
\begin{tabular}[pos]{table spec}
the table spec 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 array has been loaded):
l | left-justified column |
c | centered column |
r | right-justified column |
p{width} | paragraph column with text vertically aligned at the top |
m{width} | paragraph column with text vertically aligned in the middle (requires array package) |
b{width} | 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 p{width}
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 \textwidth
.You can find a complete list in appendix Useful Measurement Macros.
The optional parameter pos 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:
b | bottom |
c | center (default) |
t | top |
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:
& | column separator |
\\ | start new row (additional space may be specified after \\ using square brackets, such as \\[6pt] )
|
\hline | horizontal line |
\newline | start a new line within a cell |
\cline{i-j} | partial horizontal line beginning in column i and ending in column j |
Note, any white space inserted between these commands is purely down to ones' preferences. I personally add spaces between to make it easier to read.
基本例子
[編輯]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):
|
|
Column specification using >{\cmd}
and <{\cmd}
[編輯]Using the array package, the column specification can be altered. This is done in the
argument of the tabular environment using >{\command}
for commands executed right
before each column element and <{\command}
for commands to be executed right
after each column element.
As an example: to get a column in math mode enter: \begin{tabular}{>{$}c<{$}}
.
Another example is changing the font: \begin{tabular}{>{\small}c}
to print the column in a small font.
The argument of the >
and <
specifications must be correctly balanced when it comes to {
and }
characters. This means that >{\bfseries}
is valid, while >{\textbf}
will not work and >{\textbf{}
is not valid. If there is the need to use the text of the table as an argument (for instance, using the \textbf
to produce bold text), one should use the \bgroup
and \egroup
commands: >{\textbf\bgroup}c<{\egroup}
produces the intended effect. This works only for some basic LaTeX commands. For other commands, such as \underline
to underline text, it is necessary to temporarily store the column text in a box using lrbox
. First, you must define such a box with \newsavebox{\boxname}
and then you can define:
>{\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 \unhbox
(this destroys the box, if the box is needed again one should use \unhcopy
instead) and passing it to \underline
. (For LaTeX2e, you may want to use \usebox{\boxname}
instead of \unhbox\boxname
.)
This same trick done with \raisebox
instead of \underline
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 p{...}
and >{\centering}
:
\begin{tabular}{>{\centering}p{3.5cm}>{\centering}p{3.5cm}} Geometry & Algebra \tabularnewline \hline Points & Addition \tabularnewline Spheres & Multiplication \end{tabular}
Note the use of \tabularnewline
instead of \\
to avoid a Misplaced \noalign
error.
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 you know will contain a certain amount of text, then it is recommended that you use the p attribute and specify the desired width of the column (although it may take some trial-and-error to get the result you want). Use the m attribute to have the lines aligned toward the middle of the box and the b attribute to align along the bottom of the box.
Here is a practical 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:
\documentclass{article} \usepackage[english]{babel} \begin{document} Without specifying width for last column: \begin{center} \begin{tabular}{ | l | l | l | l |} \hline Day & Min Temp & Max Temp & Summary \\ \hline Monday & 11C & 22C & A clear day with lots of sunshine. However, the strong breeze will bring down the temperatures. \\ \hline Tuesday & 9C & 19C & Cloudy with rain, across many northern regions. Clear spells across most of Scotland and Northern Ireland, but rain reaching the far northwest. \\ \hline Wednesday & 10C & 21C & Rain will still linger for the morning. Conditions will improve by early afternoon and continue throughout the evening. \\ \hline \end{tabular} \end{center} With width specified: \begin{center} \begin{tabular}{ | l | l | l | p{5cm} |} \hline Day & Min Temp & Max Temp & Summary \\ \hline Monday & 11C & 22C & A clear day with lots of sunshine. However, the strong breeze will bring down the temperatures. \\ \hline Tuesday & 9C & 19C & Cloudy with rain, across many northern regions. Clear spells across most of Scotland and Northern Ireland, but rain reaching the far northwest. \\ \hline Wednesday & 10C & 21C & Rain will still linger for the morning. Conditions will improve by early afternoon and continue throughout the evening. \\ \hline \end{tabular} \end{center} \end{document}
You get the following output:
Note that the first table is cropped: The output is wider than the page width.
Text justification in tables
[編輯]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 eqparbox
package provides the command \eqmakebox
which is like \makebox
but instead of a width argument, it takes a tag. During compilation it bookkeeps which \eqmakebox
with a certain tag contains the widest text and can stretch all \eqmakebox
es with the same tag to that width. Combined with the array
package, one can define a column specifier that justifies the text in all lines: (See the documentation of the eqparbox
package for more details.)
\newsavebox{\tstretchbox} \newcolumntype{S}[1]{% >{\begin{lrbox}{\tstretchbox}}% l% <{\end{lrbox}% \eqmakebox[#1][s]{\unhcopy\tstretchbox}}% }
Other environments inside tables
[編輯]If you use some LaTeX environments inside table cells, like verbatim or enumerate
\begin{tabular}{| c | c |} \hline \begin{verbatim} code \end{verbatim} & description \\ \hline \end{tabular}
you might encounter errors similar to
! LaTeX Error: Something's wrong--perhaps a missing \item.
To solve this problem, change column specifier to "paragraph" (p, m or b).
\begin{tabular}{| m{5cm} | c |}
Defining multiple columns
[編輯]It is possible to define many identical columns at once using the *{num}{str}
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:
|
@-expressions
[編輯]The column separator can be specified with the @{...}
construct.
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. This command kills the inter-column space and replaces it with whatever is between the curly braces. To add space, use @{\hspace{width}}
.
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:
|
|
Note that the approach outlined above won't work well if the column header is longer than any of the numbers. To center the column on the decimal separator, use the dcolumn package, which provides a new column specifier for floating point data.
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:
\begin{tabular}{|l|l|} \hline stuff & stuff \\ \hline stuff & stuff \\ \hline \end{tabular}
{|l|l|} | |
{|@{}l|l@{}|} | |
{|@{}l@{}|l@{}|} | |
{|@{}l@{}|@{}l@{}|} |
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: \multicolumn{num_cols}{alignment}{contents}
. num_cols is the number of subsequent columns to merge; alignment is, either l, c, r or to have text wrapping specifiy a width p{5.0cm}
. And contents 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 \usepackage{multirow}
[1] to the preamble. This then provides the command needed for spanning rows: \multirow{num_rows}{width}{contents}
. The arguments are pretty simple to deduce (*
for the width means the content's natural width).
|
The main thing to note when using \multirow
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 columns, there must always be ampersands in each row. The exception to this is when \multicolumn and \multirow are used to create cells which span multiple columns or rows.
Spanning in both directions simultaneously
[編輯]Here is a nontrivial example how to use spanning in both directions simultaneously and have the borders of the cells drawn correctly:
|
The command \multicolumn{1}{|c|}{...}
is just used to draw vertical borders both on the left and on the right of the cell. Even when combined with \multirow{2}{*}{...}
, it still draws vertical borders that only span the first row. To compensate for that, we add \multicolumn{1}{|c|}{...}
in the following rows spanned by the multirow. Note that we cannot just use \hline
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 \cline{2-6}
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 command \resizebox{width}{height}{object}
can be used with tabular
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.
\resizebox{8cm}{!} { \begin{tabular}... \end{tabular} }
Alternatively you can use \scalebox{ratio}{object}
in the same way but with ratios rather than fixed sizes:
\scalebox{0.7}{ \begin{tabular}... \end{tabular} }
Both \resizebox
and \scalebox
require the graphicx package.
To tweak the space between columns (LaTeX will by default choose very tight columns), one can alter the column separation: \setlength{\tabcolsep}{5pt}
.
The default value is 6pt.
Sideways tables
[編輯]Tables can also be put on their side within a document using the rotating
package and the sidewaystable
environments in place of the table environment. (NOTE: most DVI viewers do not support displaying rotated text. Convert your document to a PDF to see the result. Most, if not all, PDF viewers do support rotated text.)
\usepackage{rotating} \begin{sidewaystable} \begin{tabular}... \end{tabular} \end{sidewaystable}
When it is desirable to place the rotated table at the exact location where it appears in the source (.tex) file, rotfloat
package may be used. Then one can use \begin{sidewaystable}[H]
just like for normal tables. The 'H' option can not be used without this package.
Alternate Row Colors in Tables
[編輯]The xcolor
package provides the necessary commands to produce tables with alternate row colors, when loaded with the table
option.
The command \rowcolors{<starting row>}{<odd color>}{<even color>}
has to be specified right before the tabular
environment starts.
|
The command \hiderowcolors
is available to deactivate highlighting of a specified row.
Highlighting can be reactivated within the table via the \showrowcolors
command.
各別格子的顏色
[編輯]As above this uses the xcolor
package.
% Include this somewhere in your document \usepackage[table]{xcolor} % Enter this in the cell you wish to color a light grey. % NB: the word 'gray' here denotes the grayscale color scheme, not the color grey. `0.9' denotes how dark the grey is. \cellcolor[gray]{0.9} % The following will color the cell red. \cellcolor{red}
斜體文字
部份表格直線
[編輯]Adding a partial vertical line to an individual cell:
|
Removing part of a vertical line in a particular cell:
|
The table environment - captioning etc
[編輯]The tabular
environment doesn't cover all that you need to do with tables. For example, you might want a caption for your table. For this and other reasons, you should typically place your tabular
environment inside a table
environment:
\begin{table} \caption{Performance at peak F-measure} \begin{tabular}{| r | r || c | c | c |} ... \end{tabular} \end{table}
Why do the two different environments exist? Think of it this way: The tabular
environment is concerned with arranging elements in a tabular grid, while the table
environment represents the table more conceptually. This explains why it isn't tabular
but table
that provides for captioning (because the caption isn't displayed in the grid-like layout).
A table
environment has a lot of similarities with a figure
environment, in the way the "floating" is handled etc.
For instance you can specify its placement in the page with the option [placement]
, the valid values are any combination of (order is not important):
h | where the table is declared (here) |
t | at the top of the page |
b | at the bottom of the page |
p | on a dedicated page of floats |
! | override the default float restrictions. E.g., the maximum size allowed of a b float is normally quite small; if you want a large one, you need this ! parameter as well. |
The default is [tbp]. If you want to place a table in the place where it's declared, do not just write [h]; if the table cannot fit (because the text is near the bottom of the page, say) it will float to a dedicated page of floats (as if it were a p float) which can be some distance away in the document. A good rule of thumb is to always use htbp until the document is finished, at which stage the final float parameters can be fine-tuned.
The table
environment is also useful when you want to have a
list of tables at the beginning or end of your document with the command
\listoftables
;
it enables making cross-references to the table with:
You may refer to table~\ref{my_table} for an example. ... \begin{table} \begin{tabular} ... \end{tabular} \caption{An example of table} \label{my_table} \end{table}
The tabular* environment - controlling table width
[編輯]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.
\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*}
You will notice the @{...}
construct added at the beginning of the column description. Within it is the \extracolsep
command, which requires a width. A fixed width could have been used. However, by using a rubber length, such as \fill
, the columns are automatically spaced evenly.
The tabularx package - simple column stretching
[編輯]This package provides a table environment called tabularx which is similar to the tabular* environment, except that it has a new column specifier X (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 p column, except that the width is calculated automatically. If you use the package array, you may also apply any >{\cmd} or <{\cmd} command to achieve specific behavior (like \centering, or \raggedright\arraybackslash) as described previously.
Another option is the use of \newcolumntype in order to get selected columns formatted in a different way. It defines a new column specifier, e.g. R (in uppercase). In this example, the second and fourth column is adjusted in a different way (\raggedleft):
|
Tabularx with rows spanning multiple columns using \multicolumn. The two central columns are posing as one by using the X@{} option. Note that the \multicolumn width (which in this example is 2) should equal the (in this example 1+1) width of the spanned columns:
|
Vertically centered images
[編輯]Inserting images into a table row will align it at the top of the cell. By using the array package this problem can be solved. Defining a new columntype will keep the image vertically centered.
\newcolumntype{V}{>{\centering\arraybackslash} m{.4\linewidth} }
|
Or use a parbox to center the image.
\parbox[c]{1em}{\includegraphics{image.png}}
|
專業領域表格
[編輯]Many tables in 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 \hline\hline
" 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 \toprule
for the uppermost rule (or line), \midrule
for the rules appearing in the middle of the table (such as under the header), and \bottomrule
for the lowermost rule. This ensures that the rule weight and spacing are acceptable. In addition, \cmidrule
can be used for mid-rules that span specified columns. The following example contrasts the use of booktabs and normal LaTeX implementations (the later example requires \usepackage{booktabs}
in the preamble).
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 ctable package uses the booktabs package.
Adding rule spacing above or below \hline and \cline commands
[編輯]An alternative way to adjust the rule spacing is to add \noalign{\smallskip}
before or after the \hline
and \cline{i-j}
commands:
Normal LaTeX
\begin{tabular}{llr} \hline\noalign{\smallskip} \multicolumn{2}{c}{Item} \\ \cline{1-2}\noalign{\smallskip} Animal & Description & Price (\$) \\ \noalign{\smallskip}\hline\noalign{\smallskip} Gnat & per gram & 13.65 \\ & each & 0.01 \\ Gnu & stuffed & 92.50 \\ Emu & stuffed & 33.33 \\ Armadillo & frozen & 8.99 \\ \noalign{\smallskip}\hline \end{tabular}
You may also specify the skip after a line explicitly using glue after the line terminator
\begin{tabular}{|l|l|} \hline Mineral & Color \\[1cm] Ruby & red \\ Sapphire & blue \\ \hline \end{tabular}
表格內字體大小不同
[編輯]A table can be globally switched to a different font size by simply adding the desired size command (here: \footnotesize
) after the \begin{table}...
statement:
\begin{table}[h]\footnotesize \caption{Performance at peak F-measure} \begin{tabular}{| r | r || c | c | c |} ... \end{tabular} \end{table}
The table caption font size is not affected.
To control the caption font size, see Caption Styles.
附圖像的表格
[編輯]To add a legend to a table the caption package can be used. With the caption package a \caption*{...}
statement can be added besides the
normal \caption{...}
.
Example
\begin{table} \begin{tabular}{| r | r || c | c | c |} ... \end{tabular} \caption{A normal caption} \caption*{ A legend, even a table can be used \begin{tabular}{l l} item 1 & explanation 1 \\ \end{tabular} } \end{table}
The normal caption is needed for labels en references.
想要更複雜的?
[編輯]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
- supertabular: for tables that need to stretch over several pages
- longtable: similar to supertab.
- Note: footnotes do not work properly in a normal tabular environment. If you replace it with a longtable environment, footnotes work properly
- xtab: Yet another package for tables that need to span many pages
- tabulary: modified tabular* allowing width of columns set for equal heights
- 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
- dcolumn: decimal point alignment of numeric cells
- rccol: advanced decimal point alignment of numeric cells with rounding
總結
[編輯]This concludes discussion of basic tables. Experimentation quickly leads to mastery. The table syntax in LaTeX can look rather messy, and seeing new examples can look confusing. But hopefully, enough has been covered here so that a user can create any table needed for your papers. Unsurprisingly, LaTeX has plenty more up its sleeve, so expect a follow up tutorial covering more advanced features in the near future.