Search:   Help

Navigation

Groups

LyX documentation

Edit

Shared groups

Links

LyX /

Tables

Categories: Table
<< | Page list | >>

Table formatting

1.  Introduction

All things described in this wiki page and much more about tables and longtables is described in the EmbeddedObjects manual.

If you create a table, LyX only asks for the number of columns/rows. Some table properties like the alignment can be adjusted in the table dialog, that appears when you right-click on a table. But this dialog doesn't support all possibilities to format tables.
This page gives an overview about the missing table format options. Every section includes a small example LyX-file.

2.  Vertical alignment of cell content

For fixed-width columns/multicolumn cells, LyX lets you specify the vertical alignment (top, middle, bottom). However, it is not at all intuitive how these settings are supposed to work, and indeed the way this is done by the LaTeX package array is rather odd (compared with what word processors usually do). Here are some explanations and solutions.

First some explanations:

  1. Even though the setting of the vertical alignment applies to the given column (i.e. if you have a fixed-width column, you can only set one vertical alignment, e.g. "Bottom", for this whole column), the alignment itself applies to the current row.
  2. The vertical alignment does not apply to the given cell in the sense that the content of this cell is then positioned vertically in the cell as specified (this is what word processors usually do). Rather than that, the settings have a visual effect on the remaining cells in the current row. Vertical alignment means here: the current cell is aligned with respect to the baseline of the row. I.e., if you have a cell with three lines in a column, the vertical alignment middle will position this cell in such a way that the middle of this cell (the second line in this case) will be on the baseline with the other cells. The effect is that it looks as if all others but this cell are middle-aligned. Look below for examples of a middle-, top- and bottom-aligned three-line cell (the baseline is what is highlighted yellow).
    Not precisely, but maybe more intuitively, you can also say that all the other cells in the row are positioned in the way you specifiy the vertical align of a multiline cell.
  3. This means that the vertical alignment of a row should always be set in the cell which has the most lines, because this one corresponds to the actual row height (and any other multiline cells should be set to the default Top).
  4. The rule that vertical alignment setting applies to the whole column does not apply for multicolumn cells. This is important for some cases.

b

middle 
aligned
cell

c

b

top
aligned
cell

c

b

bottom 
aligned
cell

c

So much for theory. Now here are some scenarios:

1. Suppose you want the following layout:

multiple 
lines
b 
c 
d 
multiple 
lines
f 
g 
h 
i 

To get the contents of the first row aligned in the middle, you have to go to the first cell and specify vertical alignment "Middle". However, for the second row, you will need to do this again in the second cell, because this is the highest one in that row. So again: the vertical alignment of the contents in a row have to be set in the highest cell of that row, no matter in what column this is.

2. Now what if you want different alignments for different rows, if the highest cell is in the same column? Consider this example:

multiple 
lines
b 
c 
multiple 
lines
e 
f 
g 
h 
i 

The problem is that you have set vertical alignment "middle" in the first cell of the first row to get the content of the row vertically centered in relation to that row. Now you cannot set the vertical alignment to "bottom" to get the bottom alignment for the second row, because the setting would also apply to the first row then (remember, it always applies for the whole column). The solution is: go to the first cell of the second row, make it a "multicolumn" (even though this multicolumn then has only one cell!), specify the columns width for the multicolumn, and then select "vertical alignment bottom". This setting will then only apply to the current row!

3. Fine. But can I also get a layout like this?:

 
multiple
lines

b 
multiple 
lines
 
c 

Sure. Look at the baseline. You have to set the first multicolumn cell to top, the second to bottom. So I guess you got the idea now.

3.  Multirows

Example file: table-multirow.lyx

LyX supports multicolumns but no multirows. So we have to use a bit ERT. At first we need to load the LaTeX-package multirow in the preamble with the command

\usepackage{multirow}

Multirows are created with the command

\multirow{number of rows}{cell width}{cell entry}

To create the following table

a 
b 
c 
multirow 
entry
e 
f 
h 
i 

we create a 3 × 3 table. To get rid of the line above the last cell in the first column, we mark this cell as multicolumn in the table dialog and unset the upper border in the borders dialog.
The multirow is now created in the second row of the first column. As we are using a LaTeX-command, switch to ERT with the shortcut C-l and type in the command

\multirow{2}{2.5cm}{

According to the command definition the multirow spans now two rows and has a width of 2.5 cm. The text follows outside the ERT-box and the command is finished with a right brace } in another ERT-box at the end of the text.
At last we have to center the text, because \multirow left-aligns texts by default. To override the default, we renew the command \multirowsetup with the preamble line

\renewcommand{\multirowsetup}{\centering}

Now all entries of multirow cells in the document are centered. If centering is only needed for several tables, you can renew the command in an ERT-box just before the table instead of the preamble line. If you want to right-align the text, replace \centering by \raggedleft. To return to left-alignment use \raggedright.

4.  Multiple lines in one table cell

Example file: table-multiple_lines.lyx

Adjusting a fixed width for a column, enables to enter text as a paragraph with multiple lines and hyphenations.

We want to create the following table:

multiple 
lines
b 
c 
d 
e 
f 
g 
h 
i 

We create a 3 × 3 table, mark the first cell and right-click on it. In the appearing table dialog we adjust a cell width of 2.5 cm and choose centered for the vertical and horizontal alignment.
As our text is smaller than than 2.5 cm, only one line will appear. To get two lines, we add a line break with the command

\linebreak

in ERT. Note that there must be no space between the last word (where you want the line to break) and the \linebreak command.
Now we want to center the text inside the two other cells of the first row vertically:
We right-click in the second cell, adjust a fixed width of 0.5 cm and choose centered alignments. We do the same for the third cell of the row.

If we have a long word in a cell with a fixed width, it can't be hyphenated by LaTeX if it is the first entry. Therefore we need to insert something, to make the word not be the first entry:
We add the command

\hspace{0pt}

in ERT before the word. As the space is zero, it doesn't change the output.

5.  Multicolumns

Example file: table-multicolumn.lyx

LyX supports multicolumns directly, but we have to take notice of the cell width of the columns spanned by the multicolumn cell.

We want to create for example this table:

multiple lines 
in a multicolumn
c 
d 
e 
f 
g 
h 
i 

We mark the first two cells in the first row of the 3 × 3 table and right-click on them. Now we choose multicolumn, centered alignment and a width of 2.5 cm.
The spanned columns should have exactly the half width of the multicolumn cell, so that we would adjust a width of 1.25 cm for the first column. The second column has then automatically a width of (multicolumn width - width of first column).
But in the output we can see, that is the first column has not the half width of the multicolumn cell. The reason is, that the given width wg is not the total width Wtot of the cell. The total width of n table cells Wtot n can be calculated to

Wtot n= n · (wg n + 2 · \tabcolsep) + (n + 1) · \arrayrulewidth    (1)

\tabcolsep is the LaTeX-length between the cell text and the cell border, its default value is 6 pt. \arrayrulewidth is the thickness of the cell border line, the default is 0.4 pt.

The total width of a multicolumn Wtot mult is

Wtot mult = wg mult + 2 · \tabcolsep + 2 · \arrayrulewidth    (2)

By setting equation (1) and (2) equal we can calculate the needed wg, so that the column has a total width of Wtot mult / n:

wg n = ( wg mult + (1 - n) · (2 · \tabcolsep + \arrayrulewidth) ) / n    (3)

I our case we have n = 2, wg mult = 2.5 cm and the default values for the lengths, so that equation (3) becomes

wg 2 = 1.25 cm - 6.2 pt    (4)

To enable calculations in LaTeX, we have to load the LaTeX-package calc with the preamble line

\usepackage{calc}

LyX does not allow to calculate lengths in the width-field of the table dialog. Therefore, we have to format the column by inserting a LaTeX-argument in the dialog. Here is an overview about the arguments:

  • p{width} creates cell with a fixed width, its text is vertically top-aligned
  • m{width} creates cell with a fixed width, its text is vertically centered
  • b{width} creates cell with a fixed width, its text is vertically bottom-aligned

By entering a LaTeX-argument, we overwrite all cell properties adjusted in the table dialog. (LyX shows the old properties anyway, but that is a bug.) As we want to center the text horizontally, we add the command \centering. You can now use the following LaTeX-argument for the first spanned column:

|>{\centering}m{1.25cm-6.2pt}

The bar | at the beginning draws the border line and the command >{ } means, that the commands inside the braces are applied before the cell is created.

Although we have chosen centered alignment for the text of the multicolumn cell, it is still left aligned. This is the case, because LyX applies the alignment only to single columns. So we have to use for the multicolumn cell this LaTeX-argument:

|>{\centering}m{2.5cm}|

6.  Dashed lines in tabular columns and rows

Example file: table-dashedlines.lyx

LyX doesn't natively support dashed lines, so you have to use ERT. Load the LaTeX-package arydshln in the preamble with the command

\usepackage{arydshln}

To make a vertical line dashed, enter the colon : together with the character for the horizontal alignment as LaTeX-argument in the table cell dialog. (The table cell dialogue can be accessed by right clicking in that cell and going to "More... > Settings..." or by placing your cursor in that cell and following the "Edit" menu to "Table Settings...".) For example, to make a center-aligned column have dashed lines on its right, highlight the column and go to the table cell dialogue and enter "c:" in the "LaTeX argument" box. You will then probably need to select the column to the right and turn off the solid line on its left if you do not want both a dashed line on the left and a solid line on the right.

For a horizontal dashed line add the command \hdashline in ERT as first element of the first cell in the table row.

For multicolumn dashed lines use the command \cdashline{linenumber} in ERT as first element of the first cell in the table row. If you have for example a multicolumn spanning over column 4 and 5 and you want to have it a dashed line above, add the command \cdashline{4-5} as first element of the first cell in the row of the multicolumn.

Note: The used LaTeX-package arydshln is apparently not compatible with the LaTeX-package colortbl (used in the next section to produce colored tables). That means that colored tables cannot have dashed lines.

7.  Colored tables

Example file: table-color.lyx

To create colored tables, we need the LaTeX-package colortbl, that is loaded in the preamble with the line

\usepackage{colortbl}

The color of a column is adjusted with the command

\columncolor{name of color}

inside the command >{ }. The following color names are predefined:

red, green, yellow, blue, cyan, magenta, black and white

We also define our own color with the command

\definecolor{color name}{color model}{color values}

The color model can be

  • cmyk: cyan magenta yellow black
  • rgb: red, green blue
  • gray

and the color values are comma separated numbers between 0 and 1 describing the factor for the corresponding color of the color model.

We can e.g. define the color "darkgreen" in the preamble with
\definecolor{darkgreen}{cmyk}{0.5, 0, 1, 0.5}

and the color "lightgray" with
\definecolor{lightgray}{gray}{0.8}

As we want to color the first column with darkgreen, we insert

>{\columncolor{darkgreen}\centering}c

as LaTeX-argument for this column.

Lines are colored with the command

\rowcolor{name of color}

that is inserted in the first cell of the line as ERT.

Cells are colored with the command

\cellcolor{name of color}

that is inserted at the beginning of the cell as ERT.

To color the characters in the table, mark the cells and use the LyX menu Layout→Character. But if there is ERT, mark only the characters. Otherwise the colored ERT will cause LaTeX-errors.

8.  Customized table cell format

Several LaTeX commands can be used to improve the format of a LaTex table. Several examples are given below. In some cases, you can avoid using ERT entirely by simply switching to the "Formal" style which uses the LaTeX package "booktabs" internally.

Example file: table-customization.lyx

8.1  Formal-style tables using booktabs

The http://en.wikibooks.org/wiki/LaTeX/Tables#Professional_tables "booktabs" package gives a professional look(approve sites) by not using vertical borders and by adjusting the spacing above and below the horizontal borders. To enable the "booktabs" style, right-click the table and select "Settings." Under the "Borders," tab, in the "Style" box, select the "Formal" bullet. Hover over the bullet to see a description: "Use the formal (a.k.a. booktabs) border style (no vertical borders)." In addition to not using vertical borders by default, the booktabs style adjusts the horizontal border widths and the spacing to create a professional-looking table.

8.2  Self-defined table cells

Calculating the needed width for spanned columns like in the section multicolumn is very annoying if you have several tables with multicolumn cells. To make life easier, one can define a cell/column format in the preamble, so that it can be used in all tables of the document. The format is defined with the command

\newcolumntype{name of format}[number af arguments]{commands}

The format name may only consist of one letter. The letters
b, c, l, m, p and r
are predefinied and can't be used. But all letters are allowed as capitals.

For multicolumn cells:, we can define

\newcolumntype{M}[1]{>{\centering\hspace{0pt}}m{#1}}

where \hspace{0pt} avoids the problem of hyphenating the first word, as described in section "Multiple lines in one table cell". With this, we can simply enter

|M{width}

as LaTeX-argument in the table dialog to have a centered multicolumn cell with a fixed width.

For cells spanned by a multicolumn cell:, we can define

\newcolumntype{S}[2]
   {>{\centering\hspace{0pt}}m{(#1+(2\tabcolsep+\arrayrulewidth)*(1-#2))/#2}}

We can now enter

|S{width of multicolumn cell}{number of spanned columns}

as LaTeX-argument of the column. This has the advantage, that the needed width is automatically calculated with eqution (3).

For colored columns:, we can define

\newcolumntype{K}[1]{>{\columncolor{#1}\hspace{0pt}}c}

The c creates a column with a flexible width whose text is horizontally centered. We can now enter

K{color name}

as LaTeX-argument.

8.3  Extra height

Large letters or those with a bigger height like b, d etc., often have not enough space between them and the upper cell border. With the preamble line

\setlength{\extrarowheight}{2pt}

one can add 2 pt extra height. Although this often looks better, it has the disadvantage that the cell texts are no more exactly vertically centered.

When math fractions are entered in a table, sometimes there is not enough space between them and both the upper and lower cell border. With the preamble line

\renewcommand*\arraystretch{1.5}

the cells are stretched vertically, creating sufficient room. This preserves vertical centering.

9.  Captions in Longtables

New, native solution:

A longtable cannot be put into a table float because floats can only be on one page. However you can set caption for longtables which are not inside table float. To do this:

right click on table row -> more -> settings -> longtable -> Caption: on

Then after applying settings you can input caption into special box just like in table float.

Old, workaround solution:

Example file: table-longtable-caption.lyx

Therefore LyX's caption layout cannot be used for longtables.

To add a caption for longtables, a dirty hack is needed:

\caption[short title]{full title}\\%

%

%

1

2

3

a

b

c

d

e

f

1. Create a longtable

2. Mark the first row an disable its upper line

3. Insert the following command as ERT into the first table cell:
    \caption[short title]{full title}\\%

4. Insert a % as ERT into every cell of the first row

The \caption command is used like for normal captions, the short title that will appear in the LOT instead of the full title is optional. The % in the table cells omits the vertical line between the the cells. The first table row is now only a dummy row for the caption, the actual table starts with the second row.

10.  Footnotes in tables

Footnotes do not work in tables (in ordinary tables, that is -- they do work in longtables): The footnote number is printed, but the text is omitted. This is, unfortunately, a LaTeX restriction. There are several ways to work around the problem, though, depending if your table is inside a float or not. Here is a selection of possibilities (have a look at the TUG FAQ for more information).

10.1  Table outside float

  1. One way is to put in the preamble
    \usepackage{footnote}
    \makesavenoteenv{tabular}
  2. Another is to put in the footnote \footnotemark and outside, just behind the table \footnotetext{text of the footnote}, both in ERT. Note, however, that this method only works if you have just one footnote.
  3. If you have more than one footnote, the following trick helps: put \footnotemark commands inside the table where the footnote number should appear. Outside, again just behind the table, insert \addtocounter{footnote}{-n}, where n is the number of footnotes you have just inserted into the table. Finally, insert \stepcounter{footnote}\footnotetext{footnote text} commands containing the texts of each footnote. Take care that you use the footnotemark and footnotetext commands in pairs!

10.2  Table inside float

This is more tricky, since the float is floating, and the footnotes are floating as well (which makes it very difficult to handle footnotes).

  1. The easieast way is to put the table in a minipage (Insert→Box). This will always give you footnotes, but they are not part of the ordinary footnote apparatus, but placed directly underneath the table (and separately numbered). Note that the Box (Minipage) doesn't tolerate floats, so that the table itself should be outside a float (and, in this case, within the Box). This method can cause the table with footnotes to appear below any normal footnotes on the same page. A solution is to add \usepackage[bottom]{footmisc} to the preamble (source: http://skalkoto.blogspot.com/2008/01/latex-and-footnotes.html(approve sites)). A float cannot be place in a box, but a box can be placed inside a float. Footnotes work when placed in a table itself placed in a box itself placed in a float.
  2. The packages threeparttable and ctable provide proper table notes (which are also different from the normal footnotes). The threeparttable package can be used with Lyx tables and Lyx tables floats by inserting \begin{threeparttable} at the beginning of the Lyx table float (before the table caption) and \begin{tablenotes} \item [a] the first note ... \end{tablenotes} \end{threeparttable} at the end of the Lyx table float. The more powerful ctab package, however, can only be used in ERT mode directly, because the LaTeX table code looks different from standard LaTeX tables and is not (yet) supported natively by LyX.
  3. If you really really need "ordinary" footnotes in a floating table (which is not recommended), you have to use the \footnotemark/\footnotetext method described above, but place the \footnotetext in the text next to the place where the float is put in the output. Note that this is highly fragile, and you have to check everytime you export/view your document, if the table placement (and hence the footnote) is still there.

11.  Import/paste into a Table from Excel or other Spreadsheet

See Tips.

12.  Link to an external spreadsheet file

See this Example. This is linking, not a copying technique. Changes to the spreadsheet will be reflected in LyX automatically.

13.  Scaling tables

Example file: scaling-tables.lyx

Tables can be scaled. Scaling may be utilised when a table exceeds the paper width, but there are other practical applications as well. To scale a table in LyX, create the table as usual. Make sure that the graphicx package is loaded in the preamble:

\usepackage{graphicx}

You can then put the table in a \resizebox in ERT with the syntax

\resizebox{width}{height}{argument}

where argument is in this case the table and width and height can be specified using any of the usual parameters like cm, em, pt and so on.

If you want to keep the aspect ratio of your table, you can set ! as the height parameter,

\resizebox{\textwidth}{!}{argument}

as in the example file.

Since the table (the argument) needs to be enclosed in braces {}, you need to enclose your table in two ERT commands. Put

\resizebox{width}{height}{

before the table in ERT and the closing brace

}

after it.

You can align scaled tables, and they also work in a table float. See the sample file for an example.

14.  Decimal alignment of columns

Section 2.12.2 of the Embedded Objects Manual manual discusses pros and cons of various ways to align column content around a character (such as a decimal separator). If the column will contain only decimal numbers, the following approach should work fairly painlessly. Add

\usepackage{dcolumn}

to the document preamble. (The dcolumn style is part of the required LaTeX tools package, so you should have it installed.) Right-click in the column to be aligned, navigate to the Table Settings tab, and enter something like D{.}{.}{3} in the LaTeX argument field. The three arguments are, respectively, the decimal separator used in the text as entered, the decimal separator to be used in the output, and the maximum number of decimal places. The third argument can be negative, in which case the column will be centered on the decimal separator; with a positive argument, the column will be right justified with the decimal separator aligned. See the package documentation for more details.

15.  Aligning text with images

Consider a table consisting of images in some columns and labels or explanatory text in other columns. The default vertical placement will align the baseline of the first line of text with the bottoms of the images in that row, as illustrated below.

label text 
image 
...
image
image 
...
image
or


label
text
image 
...
image
image 
...
image

One way to move the labels to the top of the row is to embed each image in a box (either minipage or parbox). In the vertical alignment portion of the box settings dialog, leave the box position at 'top' but change the content position to 'bottom'. This will result in the first line of label text aligning with inserted space just above the images, as illustrated next.

label text 

image
...
image

image
...
image
or
label 
text

image
...
image

image
...
image

Another approach is to leave the images alone (no boxes) and insert vertical space (Insert > Formatting > Vertical Space..., Spacing = Custom), and manually adjust the amount of space to obtain the desired effect. This eliminates the vertical space above the images, but may require some experimentation to achieve the desired positioning.

label text 
(... vertical spacing ...)
(... vertical spacing ...)
image 
...
image
image 
...
image
or
label 
text
(... vertical spacing ...)
image 
...
image
image 
...
image

16.  Getting tables to automatically scale to a specific width

The tabularx LaTeX package provides tables that scale to a given width automatically (i.e., you can define that specific columns are automatically stretched until the table reaches a predefined width). LyX does not support the tabularx package natively yet, but with the hack below, you can redefine LyX's tables to tabularx's. Note, however, that this change applies to all tables in the document, since all tables are treated as tabularx's of the predefined width.

Put the following to Document→Settings→Preamble:

%% Hack by Heiko Oberdiek (on de.comp.text.tex)
\usepackage{tabularx}

%% Redefine the standard table
\let\ORIGtabular\tabular
\let\ORIGendtabular\endtabular
\let\ORIGtabularx\tabularx
\renewcommand*{\tabularx}{%
  \def\tabular{%
    \let\endtabular\ORIGendtabular
    \ORIGtabular
  }%
  \ORIGtabularx
}

\renewcommand{\tabular}{%
%% The width of the table. Adjust if needed
  \tabularx{\linewidth}%
}

\renewcommand{\endtabular}{\endtabularx} 

In the tabular dialog, you can define which columns should be expanded by adding the character X to the LaTeX argument input field in the tabular dialog for the respective column(s).

Alternatively, to apply the hack to only specific tables in the document, you can put only the 3 definitions and the redefinition of tabularx into the preamble and then use ERT to redefine tabular and endtabular in a relevant table float (before the tabular environment). After the tabular environment, use ERT again to undo the changes:

%% ERT block 1 (before LyX tabular)
\renewcommand{\tabular}{\tabularx{\linewidth}}
\renewcommand{\endtabular}{\endtabularx} 

%% put LyX tabular here

% ERT block 2 (after LyX tabular)
\renewcommand{\tabular}{\ORIGtabular}
\renewcommand{\endtabular}{\ORIGendtabular} 

17.  Numbering rows of a table

To number the rows of a table, you can add the following to Document→Settings→Preamble:

\newcounter{trow}
\newcommand{\firstrow}{\setcounter{trow}{1}\arabic{trow}.}
\newcommand{\nextrow}{\addtocounter{trow}{1}\arabic{trow}.}

In the table cell where you want the number of the first row, insert \firstrow in ERT. Where you want subsequent row numbers, insert \nextrow in ERT. You can customize the presentation of the numbers by changing \arabic to \roman or \Roman and by changing the punctuation from a period to something else.

Table

Edit - History - Print - Recent Changes - All Recent Changes - Search
Page last modified on 2016-11-02 14:38 UTC