Skip to main content

10  Figures and tables

Figures and tables are how most scientific and technical documents communicate data and results. You often need precise control over their placement within documents, their captions, and the ability to group them into panels and cross-reference them throughout the text. Given their importance, we’ve devoted two chapters to figures and tables: this one and Chapter 11.

This chapter applies however you produce your figures and tables—whether you write them in markdown or generate them from code cells. We’ve done this on purpose, because most aspects of working with figures and tables are independent of their source. For example, document-level options that control figures and tables often apply universally, as do many layout features that involve surrounding figures or tables in additional markdown. There are a few exceptions where you’ll need to use specific attributes for markdown-based content or code cell options for computational output, and we’ll point these out clearly when they arise.

You should review Section 10.1, which explains how to translate between markdown and computational syntax for figures and tables. It also introduces what we call the fenced div syntax, which will help you understand and apply the examples used throughout the rest of both chapters.

We expect you’ll turn to these chapters to solve particular tasks with your own tables and figures. Table 10.1 points you to the relevant section.

Table 10.1: Common figure and table tasks.
How do I… See
Cross-reference a figure or table Section 10.2
Change the caption text, location, or title Section 10.3
Arrange multiple figures or tables in a panel Section 10.4
Put a figure or table in the margin, or make it wider than the text Section 10.5.1
Make a figure smaller or larger on the page Section 10.5.2
Align a figure left, center, or right Section 10.5.3
Align or size the columns of a table Section 10.5.4, Section 10.5.5
Control the size or aspect ratio of a computational figure Section 11.2.2
Control the format and styling of a computational table Section 11.3
Troubleshoot figure or table output from a package Section 11.4

10.1 Syntax variations

10.1.1 Markdown vs computational

As you read this chapter you’ll see examples of figures and tables that are produced in two ways: directly with markdown and computationally. Figure 10.1 reminds you of the syntax for figures, and Figure 10.2 for tables.

![Caption](path/to/image.jpg){#fig-id fig-alt="Alternative text"}
(a) Markdown
```{LANGUAGE}
#| label: fig-id
#| fig-cap: "Caption"
#| fig-alt: "Alternative text"

# Code to generate a single figure
```
(b) Executable code cell
Figure 10.1: Syntax for a figure with a numbered caption and alternative text produced with (a) markdown and (b) an executable code cell.
| Column 1 | Column 2 |
|----------|----------|
| Cell A   | Cell B   |

: Caption {#tbl-id}
(a) Markdown
```{LANGUAGE}
#| label: tbl-id
#| tbl-cap: "Caption"

# Code to generate a single table
```
(b) Executable code cell
Figure 10.2: Syntax for a table with a numbered caption produced with (a) markdown and (b) an executable code cell.

The key difference is that for computational figures and tables you use code cell options to specify captions, identifiers, and alternative text. When the computational engine executes a code cell that produces a table or figure, it uses the output, along with the code cell options, to construct the same markdown you would write by hand to render a figure or table. This means that for figure or table tweaks that involve setting document options or surrounding the figure or table in additional markdown, you can swap a markdown example with a computational one, and vice versa. For tweaks that involve changes to the markdown itself, like adding an attribute, you’ll usually find a corresponding code cell option for a computational output.

10.1.2 Fenced div syntax

When a figure or table is cross-referenceable (i.e., it has an identifier that starts with fig-, tbl-, or one of the other special prefixes), another syntax variant is useful—the fenced div syntax.

The fenced div syntax moves the caption and identifier outside of the image or table markdown. This provides a consistent syntax for both computational and non-computational figures and tables. For example, Figure 10.3 shows the fenced div syntax for figures.

::: {#fig-id}
![](path/to/image.jpg){fig-alt="Alternative text"}

Caption
:::
(a) Markdown
::: {#fig-id}
```{LANGUAGE}
#| fig-alt: "Alternative text"

# Code to generate a single figure
```

Caption
:::
(b) Executable code cell
Figure 10.3: Fenced div syntax for a figure with a numbered caption and alternative text produced with (a) Markdown and (b) an executable code cell.

The fenced div syntax abstracts away whether the figure or table is produced in Markdown or computationally. So, in the rest of this chapter and in Chapter 11, we’ll use the shorthand:

::: {#fig-id}
IMAGE

Caption
:::

where IMAGE could be a markdown image or a code cell generating a figure. Conveniently, even if you don’t replace IMAGE, this is valid Quarto markdown and will render like Figure 10.4.

IMAGE

Figure 10.4: Caption

The same fenced div syntax applies to tables, and we’ll use a similar shorthand:

::: {#tbl-id}
TABLE

Caption
:::

where TABLE could be a code cell generating a table, or a table written directly in Markdown as a pipe table, list table, or HTML table in a raw HTML block.

10.2 Cross-references

You were introduced to cross-references in Section 9.10. As a reminder, there are two required steps to cross-reference a figure or table:

  1. Give your figure or table an identifier that Quarto recognizes as a cross-reference; that is, one that starts with fig- or tbl- (Section 10.2.1).

  2. Refer to your figure or table using the @ syntax (Section 10.2.2).

Section 10.2.1 goes into more detail than Section 9.10, showing how to add an identifier to computational outputs and when using the fenced div syntax, in addition to markdown. Then, in Section 10.2.3, you’ll learn about creating sub-references.

This section focuses on creating and using cross-references. If you are interested in customizing the way your figures and tables are numbered or labeled, see Section 10.3.

10.2.1 Adding an identifier to a figure or table

Depending on how you create your figure or table, there are three ways to add an identifier that Quarto recognizes for cross-referencing:

  • Markdown figures or tables: as an ID attribute, starting with #, in markdown syntax
  • Computational figures or tables: as the label code cell option
  • Fenced div syntax: as an ID attribute, starting with #, in the fenced div syntax

We illustrate each of these for figures in Figure 10.5 and for tables in Figure 10.6. Figure captions and alternative text are optional, but you’ll generally include them, so our examples do too.

![Caption](path/to/image.jpg){#fig-id fig-alt="Alt text"}
(a) Markdown figure
```{LANGUAGE}
#| label: fig-id
#| fig-cap: "Caption"
#| fig-alt: "Alt text"
# Code to generate a single figure
```
(b) Computational figure
::: {#fig-id}
![](path/to/image.jpg){fig-alt="Alt text"}

Caption
:::
(c) Fenced div markdown figure
::: {#fig-id}
```{LANGUAGE}
#| fig-alt: "Alt text"
# Code to generate a single figure
```

Caption
:::
(d) Fenced div computational figure
Figure 10.5: Ways to add the identifier fig-id to a figure using (a) Markdown, (b) a computational code cell, (c) a fenced div with Markdown, and (d) a fenced div with a computational code cell.
| Column 1 | Column 2 |
|----------|----------|
| Cell A   | Cell B   |

: Caption {#tbl-id}
(a) Markdown table
```{LANGUAGE}
#| label: tbl-id
#| tbl-cap: "Caption"
# Code to generate a single table
```
(b) Computational table
::: {#tbl-id}
| Column 1 | Column 2 |
|----------|----------|
| Cell A   | Cell B   |

Caption
:::
(c) Fenced div markdown table
::: {#tbl-id}
```{LANGUAGE}
# Code to generate a single table
```
Caption
:::
(d) Fenced div computational table
Figure 10.6: Ways to add the identifier tbl-id to a table using (a) Markdown, (b) a computational code cell, (c) a fenced div with Markdown, and (d) a fenced div with a computational code cell.

For figures and tables you’ll usually use the prefixes fig- and tbl- respectively, but see Section 9.10 for other available prefixes. For working examples of computational figures and tables with cross-references, see Chapter 11.

TipAnything can be a “Figure”

Quarto doesn’t care what the content of the fenced div is. You can put anything inside: an image, a code block, a tabset, a table, markdown, etc. The label prefix determines how Quarto labels it. For example, using fig- gets you a “Figure X” regardless of the content.

10.2.2 Referring to a figure or table

To refer to a figure or table, use @ followed by the identifier (Figure 10.7 (a)). When rendered, the cross-references are replaced with the figure or table counter and become links (Figure 10.7 (b)). In HTML formats, hovering over the links also shows a preview of the figure or table. For variations on this syntax, like customizing the prefix or showing only the number, see Table 9.5.

TodoTO-DO

[MCR] Add a screenshot of the hover preview for a cross-reference in html output, e.g., the popup over a “Figure 1” link. Consider whether it belongs here or in @sec-html-reference-popups, with a link from the other.

See @tbl-id.
@fig-id shows ...
(a)
Rendered cross-references to a figure and a table shows the text 'See Table 1. Figure 1 shows...', where 'Table 1' and 'Figure 1' are clickable links.
(b)
Figure 10.7: Referring to a figure and a table using cross-references.
WarningCross-references are within document only

Cross-references are generally limited to the figures and tables within the same document. The one exception is a Quarto book project—this is your best option if cross-document (i.e., cross-chapter) cross-references are important to you. For documents in a website project, an alternative approach is to link to the figure or table identifier, as explained in Section 16.3.2.2.

10.2.3 Sub-references

Sub-references let you refer to one part of a multi-part figure or table, for example “Figure 1 (a)”. To create sub-references, nest your cross-referenceable elements inside a parent fenced div with a caption and an identifier. The children’s identifiers must use the same prefix as the parent’s.

For example, here the parent div has the identifier fig-animals and contains two markdown images, each with its own fig- identifier:

::: {#fig-animals}

![Elephant](images/elephant.png){#fig-elephant fig-alt="Line drawing of an elephant."}

![Panther](images/panther.png){#fig-panther fig-alt="Line drawing of a panther."}

Two animals.
:::

Use @fig-animals to refer to the whole figure (“Figure 1”), and @fig-elephant to refer to one part (“Figure 1 (a)”). The captions of the children become sub-captions. Figure 10.8 shows the result, with a sentence that uses both cross-references.

A rendered figure with a line drawing of an elephant captioned '(a) Elephant' above a line drawing of a panther captioned '(b) Panther', and the overall caption 'Figure 1: Two animals.' Below it, the text 'Figure 1 shows two animals. Figure 1 (a) is an elephant.' with both references as links.
Figure 10.8: The fig-animals example in html output. The sub-figures are labeled (a) and (b), and the sub-reference renders as “Figure 1 (a)”.

When the children become more complicated, we recommend using an explicit fenced div for each one. For example, the general structure becomes:

:::: {#fig-main}

::: {#fig-sub1}
CONTENT 1

Sub-caption 1
:::

::: {#fig-sub2}
CONTENT 2

Sub-caption 2
:::

Main caption
::::

Here, CONTENT can be any markdown or code cell output.

We’ve used additional colons (:) on the outer div to help you see the nesting, but they aren’t required.

If the children all come from one code cell that makes several outputs of the same type (all figures or all tables), you can use the fig-subcap or tbl-subcap code cell options instead. See Section 11.2.4 for figures and Section 11.3.2 for tables.

By default, the children are placed one after the other. To arrange them in rows and columns, nest a fenced div with layout attributes inside the parent, as shown in Section 10.4.

10.3 Captions

A caption has two parts: the caption text you write, and, for cross-referenceable figures and tables, a title and number that Quarto adds (e.g., “Figure 1:”). Table 10.2 outlines the caption tasks we cover in this section.

Table 10.2: Common caption tasks covered in this section.
To… Use See
Write a long caption The last paragraph of a fenced div Section 10.3.1
Include a computed value in a caption Inline code in a fenced div caption Section 10.3.2
Move captions above, below, or into the margin cap-location, fig-cap-location, tbl-cap-location Section 10.3.3
Change “Figure” or “Table”, the style of the number, or the “:” between them crossref options in the document header or _quarto.yml Section 10.3.4

There are four places to set the caption text:

  • Markdown figures: the text in the square brackets, ![Caption](path/to/image.jpg).
  • Markdown tables: the line that starts with a colon, : Caption, directly after the table.
  • Computational figures and tables: the fig-cap or tbl-cap code cell option.
  • Fenced div syntax (Section 10.1): the last paragraph inside the div, for both markdown and computational content.

The fenced div syntax is more verbose. But because its caption is an ordinary markdown paragraph, not a one-line YAML string, it is useful in two situations: long captions and dynamic captions.

The fenced div syntax only gives you a caption when the div’s identifier starts with a cross-reference prefix, such as fig- or tbl-.

10.3.1 Long captions

A long caption is hard to edit as a code cell option, because it must be a valid YAML string on one line. In a fenced div, the caption is a markdown paragraph, so you can break lines where it makes sense and use markdown formatting. In this example, IMAGE is a markdown image or a code cell that makes a figure (Section 10.1):

::: {#fig-scatter}
IMAGE

Scatter plot of bill length (mm) against bill depth (mm) for three penguin species.
The species form separate clusters:
**Adelie** penguins have short, deep bills,
and **Gentoo** penguins have long, shallow bills.
**Chinstrap** penguins have bills as deep as Adelie penguins, but longer.
:::

The line breaks in the caption are for readability in the source; the caption renders as one paragraph.

ImportantNo multi-paragraph captions

A caption must be one paragraph. If you leave a blank line in the caption, Quarto uses only the last paragraph as the caption, and puts the earlier paragraphs in the body of the figure or table.

TodoTO-DO

[MCR] Add a screenshot showing what goes wrong with a multi-paragraph caption: the earlier paragraphs rendered in the body of the figure, and only the last paragraph as the caption.

10.3.2 Dynamic captions

A dynamic caption includes a computed value. Inline code expressions, such as `{r} nrow(penguins)`, do not run inside the fig-cap or tbl-cap options, but they do run in the caption paragraph of a fenced div. For example, the caption in Figure 10.9 includes the number of penguins in the data.

::: {#fig-scatter}
IMAGE

Bill length versus depth for `{r} nrow(penguins)` penguins.
:::
::: {#fig-scatter}
IMAGE

Bill length versus depth for `{python} len(penguins)` penguins.
:::
Figure 10.9: A dynamic caption that uses inline code.

10.3.3 Caption location

By default, figure captions are placed below figures and table captions are placed above tables. You can control this placement for figures and tables separately with the fig-cap-location and tbl-cap-location options, or use cap-location to control both. Available values for these options are top, bottom, and margin as illustrated for a table in Figure 10.10. The margin value applies only to formats that have a margin, such as html and typst (Section 9.15).

A table of penguin counts by species (Adelie 151, Chinstrap 68, Gentoo 123) with the caption 'Table 1: Penguins sampled from the Palmer Archipelago' above it.

top

The same penguin counts table with its caption below the table.

bottom

The same penguin counts table with its caption in the right margin, next to the table.

margin

Figure 10.10: A table with tbl-cap-location set to top, bottom, and margin.

You can set these options at three levels:

  • In _quarto.yml to control all figures and tables in a project:

    _quarto.yml
    cap-location: bottom
  • In the document header to control all figures and tables in a document:

    document.qmd
    ---
    title: "My Document"
    cap-location: bottom
    ---
  • On an individual figure or table. Use the code cell option for computational outputs:

    ```{LANGUAGE}
    #| label: tbl-island-count
    #| tbl-cap: "Penguins sampled from the Palmer Archipelago"
    #| cap-location: bottom
    
    # Code to generate a single table
    ```

    Or the attribute form for markdown figures or tables:

    | Island    | Count |
    |-----------|-------|
    | Biscoe    | 168   |
    | Dream     | 124   |
    | Torgersen | 52    |
    
    : Penguins sampled from the Palmer Archipelago {#tbl-island-count cap-location="bottom"}

    With the fenced div syntax, put the attribute on the div:

    ::: {#tbl-island-count cap-location="bottom"}
    TABLE
    
    Penguins sampled from the Palmer Archipelago
    :::

10.3.4 Caption titles and numbering

Quarto adds a title and a number to figures and tables that are cross-referenceable. The title and number appear in the caption, and in the inline reference. You can control these using the crossref document options described in Table 10.3 and illustrated for tables in Figure 10.11.

The caption 'Table 1: Penguins sampled from ...' above a row of the options that make it up. 'Table' is tbl-title, '1' is tbl-labels, and ':' is title-delim, each matched to its part by color.

Table caption

The text 'See Table 1 ...' above a row of the options that make up the link. 'Table' is tbl-prefix and '1' is tbl-labels, each matched to its part by color.

Inline reference

Figure 10.11: The default title and number in a table caption and in a cross-reference to the table.
Table 10.3: Options under crossref that change caption titles and numbering.
Option Controls Default
fig-title
tbl-title
Text before the number in the caption
Figure
Table
fig-prefix
tbl-prefix
Text before the number in a cross-reference
Figure
Table
fig-labels
tbl-labels
Number style
arabic
arabic
subref-labels Number style for sub-references (Section 10.2.3) alpha a
title-delim Text between the number and the caption :

You can choose from these available styles for fig-labels, tbl-labels, and subref-labels:

  • arabic: 1, 2, 3
  • roman: I, II, III
  • roman i: i, ii, iii
  • alpha a: a, b, c. To start at a different letter, give that letter, for example alpha c or alpha A.

For example, you might change the title of tables to “Sheet”, the prefix to “Sh”, the numbers to Roman numerals, and the delimiter to an em dash:

document.qmd
---
title: "My Document"
crossref:
  tbl-title: Sheet
  tbl-prefix: Sh
  tbl-labels: roman
  title-delim: "—"
---

Figure 10.12 shows the result.

The caption 'Sheet I— Penguins sampled from ...' above a row of the options that make it up. 'Sheet' is tbl-title, 'I' is tbl-labels, and the em dash is title-delim, each matched to its part by color.

Table caption

The text 'See Sh I ...' above a row of the options that make up the link. 'Sh' is tbl-prefix and 'I' is tbl-labels, each matched to its part by color.

Inline reference

Figure 10.12: A table caption and cross-reference with the custom title, prefix, numbering, and delimiter.

To apply these options to all documents in a project set them in _quarto.yml.

TipCustom cross-reference types

The crossref options change all figures or all tables in a document. To keep the defaults for figures and tables and add a different kind of numbered element (for example, “Supplementary Table S1”), define a custom cross-reference type. See Custom Cross-Reference Types in the Quarto documentation.

10.4 Panel layout

Panel layouts arrange content in a grid with the layout-ncol, layout-nrow, or layout attributes (Section 9.15). This section covers the most common cases for figures and tables: arranging them in a grid, grouping them under a shared caption, and aligning them within the grid.

10.4.1 Arranging multiple figures and tables

Recall from Section 9.15 that you place content in a grid with a fenced div with the layout-ncol attribute. Put each element of the panel in its own fenced div, as shown in Figure 10.13.

:::: {layout-ncol="2"}
::: {}
CONTENT 1
:::

::: {}
CONTENT 2
:::
::::

Two placeholders, CONTENT 1 and CONTENT 2, side by side, with no captions and no numbers.

Figure 10.13: Content side by side. Neither item is cross-referenceable.

Figure 10.13 arranges the content in two columns, layout-ncol="2". Increase layout-ncol to add additional columns. If you have more than layout-ncol elements, Quarto adds rows to accommodate them.

The placeholders CONTENT 1 and CONTENT 2 can be anything, including a figure or table: a Markdown image, a Markdown table, or a code cell that produces a figure or table.

Neither element in Figure 10.13 is cross-referenceable. To make one or more cross-referenceable elements, add identifiers. Add an identifier with a cross-reference prefix to each inner div to make each item its own cross-referenceable figure or table (Figure 10.14). Add an outer div with an identifier around the layout div to make one cross-referenceable figure from the whole panel (Figure 10.15). Do both to make one cross-referenceable figure with sub-figures (Figure 10.16).

:::: {layout-ncol="2"}
::: {#fig-1}
CONTENT 1

Caption 1
:::

::: {#tbl-1}
CONTENT 2

Caption 2
:::
::::

Two separately outlined placeholders, CONTENT 1 and CONTENT 2, side by side, captioned Figure 1: Caption 1 and Table 1: Caption 2.

Figure 10.14: Cross-referenceable figures or tables side by side. Each item has its own caption and number, here “Figure 1” and “Table 1”. Because each item is cross-referenced on its own, the prefixes can differ.
::::: {#fig-main}
:::: {layout-ncol="2"}
::: {}
CONTENT 1
:::

::: {}
CONTENT 2
:::
::::

Main caption
:::::

One outlined figure around two uncaptioned placeholders, CONTENT 1 and CONTENT 2, with one caption below: Figure 1: Main caption.

Figure 10.15: One cross-referenceable figure that contains both items. You can refer to the whole figure, but not to the items inside it. The prefix of the outer div decides the type, so the whole panel is a figure, even though one item is a table.
::::: {#fig-main}
:::: {layout-ncol="2"}
::: {#fig-sub1}
CONTENT 1

Sub-caption 1
:::

::: {#fig-sub2}
CONTENT 2

Sub-caption 2
:::
::::

Main caption
:::::

One outer figure around two outlined sub-figures, CONTENT 1 and CONTENT 2, captioned (a) Sub-caption 1 and (b) Sub-caption 2, with Figure 1: Main caption below both.

Figure 10.16: One cross-referenceable figure with sub-figures. The inner captions become sub-captions. The prefix of the inner elements must match that of the outer element, all fig- in this example.

In Figure 10.16, use @fig-main to refer to the whole figure (“Figure 1”), and @fig-sub1 to refer to one part (“Figure 1 (a)”), as described in Section 10.2.3.

TipUse separate divs

Mixing cross-reference identifiers and layout attributes or column classes on the same fenced div, e.g., {#fig-id layout-ncol="2"}, often works, but it can give unexpected results in some cases. If it does, use one fenced div for the cross-reference and a separate, nested fenced div for the layout.

If one code cell makes all the figures or tables, you can use layout-ncol as a code cell option instead of a fenced div:

```{LANGUAGE}
#| label: fig-id
#| fig-cap: "Main caption"
#| fig-subcap:
#|   - "Sub-caption 1"
#|   - "Sub-caption 2"
#| layout-ncol: 2

# Code to generate two figures
```

See Section 11.2.4 and Section 11.3.2 for working examples with sub-captions. When it is appropriate, the code cell option has concise syntax, but you’ll need to switch to a fenced div if you want to mix figures, tables, markdown, or code cell output in the same panel.

10.4.2 Rows, columns, and custom grids

layout-ncol sets the number of columns, and Quarto adds rows as necessary. layout-nrow sets the number of rows, and Quarto adds columns as necessary. Each item gets the same width.

For different widths or a different number of items in each row, use the layout attribute. Its value is an array of rows. Each row is an array of numbers that give the relative width of each item. For example, layout="[[1,1],[1]]" puts two items of equal width in the first row and one item at full width in the second row (Figure 10.17).

:::: {layout="[[1,1],[1]]"}
::: {}
CONTENT 1
:::

::: {}
CONTENT 2
:::

::: {}
CONTENT 3
:::
::::

Two placeholders of equal width, CONTENT 1 and CONTENT 2, side by side in the first row, and one full-width placeholder, CONTENT 3, in the second row, with no captions.

Figure 10.17: A custom grid with layout="[[1,1],[1]]": two items in the first row and one item at full width in the second row.

As with layout-ncol, add identifiers to the inner or outer divs to make the items, or the whole panel, cross-referenceable.

The numbers are relative, so layout="[[70,30]]" gives a row where the first item is 70% of the width and the second item is 30%. A negative number adds empty space. For example, layout="[40,-20,40]" puts a 20% gap between two items.

10.4.3 Alignment in a panel

Items in a row are frequently different heights, for example, a tall figure next to a short table. Use layout-valign to set the vertical alignment of the items in each row: top, center, or bottom (Figure 10.18).

:::: {layout-ncol="2" layout-valign="bottom"}
::: {}
CONTENT 1
:::

::: {}
CONTENT 2
:::
::::

A tall placeholder, CONTENT 1, next to a short placeholder, CONTENT 2, with their bottom edges aligned.

Figure 10.18: Content of different heights aligned with layout-valign="bottom". The bottom edges of the items line up.

Use layout-align to set the horizontal alignment of each item in its cell: left, center, or right. You can also set layout-align and layout-valign as code cell options.

10.5 Position, size, and alignment

You can move a figure or table into a different column of the page, change the width of a figure, and align a figure inside its container. Inside a table, you can also change the alignment and width of each column. For slides, see Section 14.5.3.2 for the output-location code cell option, which can put output on the next slide or next to the code.

10.5.1 Position relative to the page

As you saw in Section 9.15, fenced divs with .column- classes put content in different columns of the page. To move a figure or table, wrap its fenced div in a fenced div with a .column- class. For example, to give a wide figure the full width of the screen, use .column-screen:

:::: {.column-screen}
::: {#fig-id}
IMAGE

Caption
:::
::::

For a small figure that supports the main text, use .column-margin to put it in the margin. The figure keeps its caption and number. As with panel layouts, keep the column class and the identifier on separate fenced divs.

For a code cell, use the column code cell option instead of a class. The value is the class name without the column- prefix:

```{LANGUAGE}
#| label: fig-id
#| fig-cap: "Caption"
#| column: screen

# Code to generate a single figure
```

The fig-column and tbl-column code cell options are similar, but they move only the figure or table output, not the other output of the cell.

To set a default for the whole document, use these options in the document header:

report.qmd
---
fig-column: page
tbl-column: margin
---

In the header, fig-column and tbl-column apply to every cross-referenceable figure or table, from markdown or from a code cell. Figures and tables without an identifier stay in the body column. column in the header applies to both figures and tables, but not to other cell output. Figure 10.19 shows the result in html output.

A scatterplot of penguin bill depth versus bill length, colored by species, that spans the full width of the page, wider than the paragraphs above and below it.
(a) column: screen
A paragraph of placeholder text with a small version of the penguin scatterplot in the right margin beside it.
(b) column: margin
Figure 10.19: A figure in different columns of the page: (a) the full width of the screen and (b) the margin. Columns apply to the html and typst formats.

You can find all the possible column values in the Quarto documentation on Article Layout.

In html output, columns collapse on narrower screens; see Section 12.13.1.

10.5.2 Figure width

To set the width of a figure in the document, add a width attribute with a percentage of the figure’s container, usually the body text, or the column (Section 10.5.1) or panel cell (Section 10.4) the figure sits in:

![Caption](path/to/image.png){#fig-id width="50%"}

This scales the display of the figure; the image itself is unchanged.

TodoTO-DO

[MCR] Add a screenshot of the same image at its natural width and with width="50%".

Notewidth vs. fig-width

width sets the display width of a figure in the document; fig-width sets the size of the image a code cell generates. See Section 11.2.2 for fig-width.

By default, an image displays at its own width: an image narrower than its container displays as is, and an image wider than its container scales down to fit. Setting width overrides both behaviors, scaling an image up or down to the given share of its container.

For a figure from a code cell with the knitr engine, use the out-width code cell option. Its value uses the same units as the width attribute:

```{r}
#| label: fig-id
#| fig-cap: "Caption"
#| out-width: 50%

# Code to generate a single figure
```

There’s also an out-height code cell option for the display height. Set only one of out-width and out-height so the figure keeps its aspect ratio.

The jupyter engine has no code cell option for the width of a figure in the document.

NoteAbsolute widths

You can also give width an absolute length in inches, centimeters, or millimeters, for example width="2in". A number with no unit is a width in pixels. An absolute width does not change with the container, so a percentage is usually a better choice.

10.5.3 Figure alignment

Figure alignment is the horizontal position of a figure in its container. Alignment has a visible effect only when the figure is narrower than its container (Section 10.5.2).

Use fig-align to change the alignment. Its values are default (the default for the output format), left, center, and right. Figure 10.20 shows the effect of left, center, and right.

A scatterplot aligned to the left of the page.

fig-align: left

A scatterplot centered on the page.

fig-align: center

A scatterplot aligned to the right of the page.

fig-align: right
Figure 10.20: Examples showing the effect of different fig-align settings: left, center, and right.

To align all the figures in a document, set fig-align as a document option:

document.qmd
---
fig-align: left
---

This applies to figures from markdown and from code cells.

To align one figure, and override the document option, add a fig-align attribute to a markdown image:

![Caption](path/to/image.jpg){#fig-id fig-align="right"}

Or, for a figure from a code cell, use the fig-align code cell option:

```{LANGUAGE}
#| label: fig-id
#| fig-cap: "Caption"
#| fig-align: right

# Code to generate a single figure
```

10.5.4 Table column alignment

Column alignment is the horizontal position of the content in each cell of a table column. By default, the output format sets the alignment. How you change it depends on how you make the table: as a pipe table, as a list table, or with a code cell.

To align the columns of a pipe table, add colons to the separator row. A colon on the left aligns the column to the left, a colon on the right aligns it to the right, and colons on both sides center it. This table aligns the first column to the left, the second column to the center, and the third column to the right:

| Algorithm           | Accuracy | Time  |
|:--------------------|:--------:|------:|
| Random Forest       | 96.7%    | 0.12s |
| Logistic Regression | 81.2%    | 0.08s |
| Linear Regression   | 74.8%    | 0.05s |

To align the columns of a list table, add an aligns attribute to the .list-table div. Its value is a comma-separated list with one letter per column: l (left), c (center), r (right), or d (default). This list table has the same alignment as the pipe table above:

::: {#tbl-perf-align .list-table header-rows=1 aligns="l,c,r"}
Training performance

* - Algorithm
  - Accuracy
  - Time
* - Random Forest
  - 96.7%
  - 0.12s
* - Logistic Regression
  - 81.2%
  - 0.08s
* - Linear Regression
  - 74.8%
  - 0.05s
:::
TodoTO-DO

[MCR] Add a screenshot of the rendered table with left-, center-, and right-aligned columns. The pipe table and list table examples render the same, so one screenshot covers both.

For a table from a code cell, there is no code cell option for column alignment. Instead, set the alignment with the function that makes the table. A code cell can output a markdown table, for example with knitr::kable() in R or tabulate() from the tabulate package in Python. In Figure 10.21, the align argument to knitr::kable() and the colalign argument to tabulate() align the species column to the left and the count column to the right.

```{r}
penguins |>
  count(species) |>
  knitr::kable(align = c("l", "r"))

```
```{python}
from tabulate import tabulate
from IPython.display import Markdown

summary_table = (
  pl.DataFrame(penguins)
 .group_by('species')
 .len()
)
Markdown(tabulate(summary_table.to_pandas(), 
  tablefmt='pipe', headers='keys', showindex=False,
  colalign=('left', 'right')))

```
Figure 10.21: Set the column alignment of a markdown table from a code cell with the function that makes the table.

A package that makes HTML tables, such as gt in R or great_tables in Python, styles the table itself. Use the functions of the package to set the column alignment. In Figure 10.22, cols_align() aligns the count column to the right.

```{r}
penguins |>
  count(species) |>
  gt() |>
  cols_align(align = "right", columns = n)
```
```{python}
(
    pl.DataFrame(penguins)
    .group_by("species")
    .len()
    .pipe(GT)
    .cols_align(align="right", columns="len")
)
```
Figure 10.22: Use the gt or great_tables function cols_align() to set the column alignment of an HTML table.

10.5.5 Table column widths

Column width is the proportion of the table width that a column uses. By default, the widths depend on the content of the columns.

To set the column widths of a pipe table, add a tbl-colwidths attribute after the caption. Its value is an array of percentages, one per column. This table gives the first column 80% of the width, and the other two columns 10% each:

| Algorithm           | Accuracy | Time  |
|:--------------------|:--------:|------:|
| Random Forest       | 96.7%    | 0.12s |
| Logistic Regression | 81.2%    | 0.08s |
| Linear Regression   | 74.8%    | 0.05s |

: {tbl-colwidths="[80, 10, 10]"}
TodoTO-DO

[MCR] Add a screenshot of the rendered 80/10/10 table. Consider pairing it with the rendered gt/great_tables example (tab_options() + cols_width()) below, to show markdown and HTML tables reaching the same layout in different ways.

For a list table, you can add the same tbl-colwidths attribute to the .list-table div. Or, use the list table attribute widths, with a comma-separated list of widths:

::: {#tbl-perf-widths .list-table header-rows=1 widths="80,10,10"}
Training performance

* - Algorithm
  - Accuracy
  - Time
* - Random Forest
  - 96.7%
  - 0.12s
* - Logistic Regression
  - 81.2%
  - 0.08s
* - Linear Regression
  - 74.8%
  - 0.05s
:::

For a code cell that outputs a markdown table, use the tbl-colwidths code cell option (Figure 10.23).

```{r}
#| tbl-colwidths: [25, 75]
penguins |>
  count(species) |>
  knitr::kable()

```
```{python}
#| tbl-colwidths: [25, 75]
from tabulate import tabulate
from IPython.display import Markdown

summary_table = (
  pl.DataFrame(penguins)
 .group_by('species')
 .len()
)
Markdown(tabulate(summary_table.to_pandas(), 
  tablefmt='pipe', headers='keys', showindex=False))

```
Figure 10.23: Use the tbl-colwidths code cell option to set the column widths of a markdown table from a code cell.

tbl-colwidths applies only to markdown tables. For an HTML table, use the functions of the package that makes it. In Figure 10.24, tab_options() makes the table the full width of its container, and cols_width() gives the species column 25% of the width and the count column 75%.

```{r}
penguins |>
  count(species) |>
  gt() |>
  tab_options(table.width = pct(100)) |>
  cols_width(
    species ~ pct(25),
    n ~ pct(75)
  )
```
```{python}
(
    pl.DataFrame(penguins)
    .group_by("species")
    .len()
    .pipe(GT)
    .tab_options(table_width="100%")
    .cols_width(species="25%", len="75%")
)
```
Figure 10.24: Use the gt or great_tables functions tab_options() and cols_width() to set the column widths of an HTML table.

To set the column widths of all the markdown tables in a document, set tbl-colwidths as a document option:

document.qmd
---
tbl-colwidths: [80, 10, 10]
---

A tbl-colwidths attribute on a table, or a tbl-colwidths code cell option, overrides the document option. A list table widths attribute does not.

10.6 Wrapping Up

You now know how to cross-reference, caption, lay out, and position any figure or table, whether it comes from markdown or code. But when code produces the output, some things are decided before Quarto ever sees it, like the size of a plot, the format of a table, or the styling a package adds. Chapter 11 covers the code cell options that control these, and how to troubleshoot output that isn’t what you expect.