Skip to main content

11  Computational figures and tables

This chapter covers topics specific to figures and tables that are the output of executable code cells. Producing figures and tables with code has many advantages:

You’ll start by reviewing the most common code cell options for figures and tables—those that add captions, identifiers, and alternative text.

We’ve split the rest of the chapter into three sections: one for figures (covering size, format, resolution, and multiple figures), one for tables (covering table formats and multiple tables), and one for troubleshooting figures and tables that don’t come out as you expect.

Much of the control of computational figures and tables comes from code cell options. To help you navigate this, and other chapters, we list the most common code cell options in Table 11.1. With one exception, we only list options common to both the knitr and jupyter engines. Use the Quarto Code Cell Reference for the full list of available options.

Table 11.1: Common code cell options for figures and tables
Option Document option Description Reference
label ID for output, also used for cross-references Section 11.1. Prefix with fig- or tbl- to number and cross-reference; see Section 10.2
fig-cap Caption for figure Section 11.1. For control over appearance see Section 10.3
tbl-cap Caption for table Section 11.1. For control over appearance see Section 10.3
fig-alt Alternative text description of the figure Section 11.1
fig-subcap Sub-captions for multiple figures produced in a single code cell Section 11.2.4
tbl-subcap Sub-captions for multiple tables produced in a single code cell Section 11.3.2
layout-ncol / layout-nrow Number of columns when arranging multiple figures or tables in a single panel For figures see Section 11.2.4, for tables see Section 11.3.2. For more complicated layouts see Section 10.4
column / fig-column / tbl-column Place figure or table in a specific column relative to page Section 10.5.1
output-location Place figure or table in a specific location relative to slide Section 14.5.3.2
fig-width / fig-height knitr engine only ☑ Size of figure in inches Section 11.2.2, also includes options for jupyter engine
out-width knitr engine only Display width of figure on the page Section 10.5.2
fig-align ☑ Alignment of figures in their surrounding container Section 10.5.3
tbl-colwidths ☑ Column widths for markdown tables Section 10.5.5
layout Layout specification when arranging multiple figures or tables in a single panel Section 10.4
layout-align / layout-valign Alignment when arranging multiple figures or tables in a single panel Section 10.4
cap-location / fig-cap-location / tbl-cap-location ☑ Location of caption relative to figure or table Section 10.3.3

A ☑ in the Document option column marks options you can also set at the document level.

NoteThe examples in this chapter

We wanted authentic examples of figures and tables generated by code in this chapter. However, the focus of this chapter isn’t on the code, and we don’t want it to distract you. To balance those objectives we’ve selected a small number of examples that we’ll repeat throughout the chapter. These examples are designed to be almost identical between R and Python, so we’ve limited ourselves to a few packages (ggplot2 and gt in R, and plotnine and great_tables in Python).

We’ve provided examples in both R and Python so you can reproduce them in your favorite language. The concepts you are learning are independent of language and package, so while the executable code is different, the code cell options and Markdown syntax are identical.

The code to generate the example figures and tables is shown without any other context. If you want to recreate them, you’ll need the setup code as shown in Figure 11.1. We also show the rendered examples without the code; that is, we set echo: false in our document header:

document.qmd
---
echo: false
---
setup.R
library(tidyverse)
library(gt)
library(palmerpenguins)

theme_set(theme_classic())

penguin_colors <- c(
  Adelie = "#FF8C00",
  Chinstrap = "#A020F0",
  Gentoo = "#008B8B"
)

penguins <- penguins |>
  drop_na(bill_depth_mm)
setup.py
import polars as pl
from plotnine import *
from great_tables import GT
from palmerpenguins import load_penguins

theme_set(theme_classic())

penguin_colors = {
    'Adelie': '#FF8C00',
    'Chinstrap': '#A020F0',
    'Gentoo': '#008B8B'
}

penguins = load_penguins()
penguins = (pl.DataFrame(penguins)
    .drop_nulls("bill_depth_mm"))
Figure 11.1: Code required before executing the examples in this chapter.

11.1 Basics

If the output of an executable code cell is a figure or a table, Quarto includes it automatically in the rendered document. For example, in Figure 11.2 the code cell produces a figure.

Some text before the code cell.

```{r}
penguins |>
  ggplot(aes(x = bill_length_mm, y = bill_depth_mm)) +
  geom_point(aes(color = species)) +
  scale_color_manual(values = penguin_colors) +
  labs(x = "Bill Length (mm)", y = "Bill Depth (mm)")

```

Some text after the code cell.
Some text before the code cell.

```{python}
(
    ggplot(penguins, aes(x="bill_length_mm", y="bill_depth_mm"))
    + geom_point(aes(color="species"))
    + scale_color_manual(values=penguin_colors)
    + labs(x="Bill Length (mm)", y="Bill Depth (mm)")
)

```

Some text after the code cell.
Figure 11.2: A document with an executable code cell that produces a figure.

When the document is rendered, the figure appears right where the code cell was (Figure 11.3).

Screenshot of Quarto HTML document with a scatterplot shown below the line of text 'Some text before the code cell' and above the line of text 'Some text after the code cell'.
Figure 11.3: A rendered document with a figure produced by a code cell.

For non-computational figures and tables, you can add context, such as a caption or identifier, using Markdown syntax. For computational ones, you use code cell options.

The most common options are:

  • label: The ID for the resulting figure or table. You must omit the #. If the label starts with fig- or tbl-, the figure or table will be numbered, and can be cross-referenced.

  • fig-cap/tbl-cap: The caption for the resulting figure or table. Use standard YAML syntax for long strings (Section 17.3.1.2) if you need to break across lines, but ensure each line starts with #|.

  • fig-alt: Alternative text for the resulting figure. There is no tbl equivalent, because tables are text-based and generally accessible to screen readers.

TodoTO-DO

[CVW] Multi-line fig-cap/tbl-cap with YAML long strings is currently not true for the jupyter engine. Check on state of https://github.com/quarto-dev/quarto-cli/issues/11290.

For example, Figure 11.4 uses the same code as Figure 11.2 but adds an identifier, caption, and alternative text with code cell options.

```{r}
#| label: fig-scatter
#| fig-cap: "Penguin bill length versus depth by species"
#| fig-alt: "Scatter plot of bill length vs. depth showing distinct species clustering."

penguins |>
  ggplot(aes(x = bill_length_mm, y = bill_depth_mm)) +
  geom_point(aes(color = species)) +
  scale_color_manual(values = penguin_colors) +
  labs(x = "Bill Length (mm)", y = "Bill Depth (mm)")

```
```{python}
#| label: fig-scatter
#| fig-cap: "Penguin bill length versus depth by species"
#| fig-alt: "Scatter plot of bill length vs. depth showing distinct species clustering."

(
    ggplot(penguins, aes(x="bill_length_mm", y="bill_depth_mm"))
    + geom_point(aes(color="species"))
    + scale_color_manual(values=penguin_colors)
    + labs(x="Bill Length (mm)", y="Bill Depth (mm)")
)

```
Figure 11.4: Basic code cell options used to add an identifier (label), caption (fig-cap), and alternative text (fig-alt) to a computational figure.

The rendered result is shown in Figure 11.5. The caption here is prefaced by “Figure 1:” because the label started with fig-, the signal that this is a cross-referenceable figure.

A scatterplot of penguin bill depth versus bill length, colored by species (Adelie, Chinstrap, Gentoo), with the caption 'Figure 1: Penguin bill length versus depth by species'.
Figure 11.5: Example output when Figure 11.4 is rendered.

Figure 11.6 demonstrates the same concept for tables. To caption a table use the tbl-cap option, and start the label with tbl- to make it cross-referenceable.

```{r}
#| label: tbl-species-count
#| tbl-cap: "Number of penguins sampled from each species in the Palmer Archipelago"

penguins |>
  count(species) |>
  gt()

```
```{python}
#| label: tbl-species-count
#| tbl-cap: "Number of penguins sampled from each species in the Palmer Archipelago"

(
  pl.DataFrame(penguins)
 .group_by('species')
 .len()
 .pipe(GT)
)

```
Figure 11.6: Basic code cell options used to add an identifier (label) and caption (tbl-cap) for a computational table.

The result is shown in Figure 11.7. The table caption is prefaced by “Table 1:” because the label started with tbl-, the signal that this is a cross-referenceable table.

Rendered table with caption above it 'Table 1: Number of penguins sampled from each species in the Palmer Archipelago'.
Figure 11.7: Example output when Figure 11.6 is rendered.

11.1.1 Fenced div syntax

For cross-referenceable figures and tables, fenced divs provide an alternative method for labeling and captioning. Instead of using the code cell options label and fig-cap/tbl-cap, you set the identifier on a fenced div, and the caption as the last paragraph inside the fenced div. The content above the caption becomes the content of the figure or table, and could be a code cell.

As a concrete example, Figure 11.8 gives the same labeled and captioned figure as the code cell in Figure 11.4. Figure 11.9 does the same for the table in Figure 11.6.

::: {#fig-scatter}
```{r}
#| fig-alt: "Scatter plot of bill length vs. depth showing distinct species clustering."

penguins |>
  ggplot(aes(x = bill_length_mm, y = bill_depth_mm)) +
  geom_point(aes(color = species)) +
  scale_color_manual(values = penguin_colors) +
  labs(x = "Bill Length (mm)", y = "Bill Depth (mm)")

```

Penguin bill length versus depth by species

:::
::: {#fig-scatter}
```{python}
#| fig-alt: "Scatter plot of bill length vs. depth showing distinct species clustering."

(
    ggplot(penguins, aes(x="bill_length_mm", y="bill_depth_mm"))
    + geom_point(aes(color="species"))
    + scale_color_manual(values=penguin_colors)
    + labs(x="Bill Length (mm)", y="Bill Depth (mm)")
)

```

Penguin bill length versus depth by species

:::
Figure 11.8: The equivalent fenced div syntax for Figure 11.4.
::: {#tbl-species-count}

```{r}
penguins |>
  count(species) |>
  gt()

```

Number of penguins sampled from each species in the Palmer Archipelago
:::
::: {#tbl-species-count}

```{python}
(
  pl.DataFrame(penguins)
 .group_by('species')
 .len()
 .pipe(GT)
)

```

Number of penguins sampled from each species in the Palmer Archipelago
:::
Figure 11.9: The equivalent fenced div syntax for Figure 11.6.

The fenced div syntax is useful if you want long captions (Section 10.3.1), dynamic captions that depend on code output (Section 10.3.2), or to combine multiple figures and tables into a single panel with a shared caption (Section 10.4).

11.2 Figures

In this section you’ll learn about figure-specific options: figure size, format and resolution, and multiple figures. For figure alignment, see Section 10.5.3. Some of these controls are document options (set in your document header and applied to all figures), some are code cell options (applied to individual code cells), and others need to be configured directly in your plotting code.

11.2.1 Default figure size

The document options fig-width and fig-height control the default size of figures produced by all the code cells in a document.

How these values are applied depends on the engine:

  • knitr: the values are passed along to the graphics device, and thus apply regardless of the package you use to create the plots.
  • jupyter: the values are used to set the default figure size for matplotlib. Many popular plotting packages, including seaborn, depend on matplotlib, and will respect these defaults. Some packages, like plotnine, don’t use matplotlib defaults but do respect the environment variables Quarto sets: QUARTO_FIG_WIDTH and QUARTO_FIG_HEIGHT.

The default values are format specific. For example, the default figure size for format: html is 7 × 5 inches, and for format: typst it is 5.5 × 3.5 inches.

You can override these defaults using fig-width and fig-height document options. For example, the following sets the default figure size to 4 × 6 inches for html output:

document.qmd
---
format:
  html:    
    fig-width: 4
    fig-height: 6
---

Set fig-width and fig-height at the top level (i.e., not nested under a format) to apply to all formats. You could also set fig-width and fig-height in _quarto.yml to apply to all documents in a project.

11.2.2 Custom figure size

The defaults set by the document options will apply to all code cells. However, you often want to customize the size and aspect ratio of individual plots. How you do this depends on the engine.

11.2.2.1 knitr

With the knitr engine, use the fig-width and fig-height code cell options, specified in inches, to customize figure size for individual plots:

```{r}
#| fig-width: 4
#| fig-height: 6

penguins |>
  ggplot(aes(x = island, fill = species)) +
  geom_bar(position = "stack") +
  scale_fill_manual(values = penguin_colors) +
  labs(x = "Species", y = "Count")

```

To set the shape of a figure rather than its exact height, use fig-asp, the ratio of height to width. For example, fig-asp: 0.618 with fig-width: 6 gives a figure about 3.7 inches tall. If you set both fig-asp and fig-height, fig-asp wins.

TodoTO-DO

[MCR] Add a screenshot comparing the same plot at the default size and with custom fig-width/fig-height (e.g., the 4 × 6 example above) or fig-asp, in html output. Make the point that because the figure scales to the body width, a smaller fig-width makes text and points look larger, and fig-height changes the shape.

11.2.2.2 jupyter

There are no fig-width or fig-height code cell options for the jupyter engine. You need to set the figure size in the code itself. This will depend on the plotting package you are using.

For plotting packages that use matplotlib and respect its defaults, you can set figure sizes using matplotlib directly.

For example, the following code creates a scatterplot of seaborn’s own penguins data using seaborn:

```{python}
import seaborn as sns
penguins = sns.load_dataset("penguins")
sns.scatterplot(
    data=penguins, x="bill_length_mm", y="bill_depth_mm", hue="species"
)
```

With no further adjustment, the size of the figure will reflect the default fig-height and fig-width document options.

To change the size of the figure you change the matplotlib default plot size using rcParams:

```{python}
import matplotlib as mpl
mpl.rcParams['figure.figsize'] = (8, 4)

sns.scatterplot(
    data=penguins, x="bill_length_mm", y="bill_depth_mm", hue="species"
)
```

This mimics the way the jupyter engine sets the default plot sizes and will apply to all plots created in subsequent code cells.

Alternatively, to apply a new default for a single plot, use rc_context:

```{python}
import matplotlib as mpl
with mpl.rc_context({'figure.figsize': (8, 4)}):
    sns.scatterplot(
        data=penguins, x="bill_length_mm", y="bill_depth_mm", hue="species"
    )
```

For packages that don’t use matplotlib, or don’t respect its defaults, you’ll need to refer to their documentation for changing plot size. For example, in plotnine you can resize a plot through the figure_size argument to the theme() function:

```{python}
(
    ggplot(penguins, aes(x="bill_length_mm", y="bill_depth_mm"))
    + geom_point(aes(color="species"))
    + scale_color_manual(values=penguin_colors)
    + labs(x="Bill Length (mm)", y="Bill Depth (mm)")
    + theme(figure_size=(8, 4))
)
```

11.2.3 Figure format and resolution

The default image format saved by the engines depends on the output format. The format chapters give each default and explain when you might choose a different one: see Section 12.12.1 for html and Section 13.8.1 for typst.

You can override the default using the fig-format document option. For example, the following sets the default figure format to svg for html output:

document.qmd
---
format:
  html:
    fig-format: svg
---

Setting fig-format at the top level applies to all output formats. You can also set fig-format in _quarto.yml, at the top level or under a format, to apply it to all documents in a project.

For raster image formats like png and jpg, you can also control the resolution of the saved image using the fig-dpi document option.

For example, the following sets the default figure resolution to 300 dots per inch (DPI) for html output:

document.qmd
---
format:
  html:
    fig-dpi: 300
---

Like fig-format, you can set fig-dpi for all formats, or for all documents in a project with _quarto.yml.

TodoTO-DO

[MCR] Add a screenshot of a zoomed-in crop of the same figure at a low fig-dpi and at 300, or as PNG next to SVG, to show the difference in sharpness.

11.2.4 Multiple figures

If your code cell produces multiple figures, you can combine them into a single panel by providing individual sub-captions for each figure using the fig-subcap code cell option. For example, Figure 11.10 produces two figures in a single code cell, and thus provides an array of two values to both fig-subcap and fig-alt. To arrange the figures in the panel, see Section 10.4.1.

```{r}
#| label: fig-scatter
#| fig-cap: Physical dimensions of penguins
#| fig-alt: 
#|   - "Scatter plot of bill length vs. depth showing distinct species clustering."
#|   - "Scatter plot of flipper length vs. body mass showing a strong positive relationship."
#| fig-subcap: 
#|   - "Penguin bill length versus depth by species"
#|   - "Penguin flipper length versus body mass by species"

penguins |>
  ggplot(aes(x = bill_length_mm, y = bill_depth_mm)) +
  geom_point(aes(color = species)) +
  scale_color_manual(values = penguin_colors) +
  labs(x = "Bill Length (mm)", y = "Bill Depth (mm)")


penguins |>
  ggplot(aes(x = body_mass_g, y = flipper_length_mm)) +
  geom_point(aes(color = species)) +
  scale_color_manual(values = penguin_colors) +
  labs(x = "Body Mass (g)", y = "Flipper Length (mm)")

```
```{python}
#| label: fig-scatter
#| fig-cap: Physical dimensions of penguins
#| fig-alt: 
#|   - "Scatter plot of bill length vs. depth showing distinct species clustering."
#|   - "Scatter plot of flipper length vs. body mass showing a strong positive relationship."
#| fig-subcap: 
#|   - "Penguin bill length versus depth by species"
#|   - "Penguin flipper length versus body mass by species"

(
    ggplot(penguins, aes(x="bill_length_mm", y="bill_depth_mm"))
    + geom_point(aes(color="species"))
    + scale_color_manual(values=penguin_colors)
    + labs(x="Bill Length (mm)", y="Bill Depth (mm)")
)


(
    ggplot(penguins, aes(x="body_mass_g", y="flipper_length_mm"))
    + geom_point(aes(color="species"))
    + scale_color_manual(values=penguin_colors)
    + labs(x="Body Mass (g)", y="Flipper Length (mm)")
)

```
Figure 11.10: An example of a code cell that produces two figures. Individual figure captions are provided as an array to fig-subcap, and alternative text descriptions are provided as an array to fig-alt.
Two scatterplots one above the other. Each plot has a caption prefaced by '(a)' and '(b)' respectively. The overall caption is 'Figure 1: Physical dimensions of penguins'.
Figure 11.11: Result of rendering the code cell with multiple figures in Figure 11.10.

When rendered, the figures are placed together in a single “Figure” where the overall caption is provided by fig-cap and prefaced by “Figure 1:”. Each individual figure in the panel has its own sub-caption prefaced by “(a)” and “(b)”. You can cross-reference the entire panel with the label, e.g., @fig-scatter, or individual figures by appending an index, e.g., @fig-scatter-1 and @fig-scatter-2.

Often the use of fig-subcap is combined with layout options to arrange the figures in a specific way. For example, the layout-ncol code cell option will arrange the figures in a specified number of columns. Adding the code cell option layout-ncol: 2 to Figure 11.10 would result in the figures laid out side by side rather than one above the other.

Using fig-subcap is a quick way to make a multi-panel figure. But if you want to mix figures and tables, control where each item appears on the page, or caption and cross-reference items your own way, we recommend one code cell per output, using fenced div syntax to label, caption, and arrange them. You can learn more about this approach in Section 10.4.

11.3 Tables

In this section you’ll learn about table-specific options, in particular choosing a table format. For column alignment and widths, see Section 10.5.4 and Section 10.5.5.

11.3.1 Table format

When you produce a computational table, the engine writes the table in a plain-text format. The most common formats are markdown pipe tables and HTML tables. Both markdown pipe tables and HTML tables are supported across all of Quarto’s output formats. The choice between them often comes down to how much control you want over the appearance of the table.

Choose:

  • Markdown: for simple tables that don’t require any row-, cell-, or column-specific formatting.

  • HTML: for more complex tables, with a structure like merged cells or hierarchical headers, or that require row-, cell-, or column-specific styling. While HTML allows for more control over the appearance of the table, not all customization will propagate through to all target formats. The best support for HTML styling is in HTML-based formats (html, dashboard, and revealjs), and typst.

Your package and function choices, along with your target format, determine which format is produced. Often the format is explicit in your code, e.g., by a call to Markdown() in Python. If it isn’t, and you aren’t sure which format you have produced, check the intermediate markdown that Quarto produces after executing your code cells (Section 11.4.2).

How Quarto handles each kind of table depends on the output format; see Section 12.12.2 for html and Section 13.8.2 for typst.

TodoTO-DO

[MCR] Add a side-by-side screenshot of the same table rendered as a markdown table from code (kable()/tabulate()) and as an HTML table from gt/great_tables, in html output. The gt one could reuse images/figure-table-basic-cell-options-table.png.

11.3.1.1 Markdown

Using the markdown pipe syntax mimics how you might write a table out by hand in Quarto (Section 9.7). There are many ways to produce a Markdown table computationally, but we highlight the most general approach for each language here.

11.3.1.1.1 R

The kable() function from the knitr package produces markdown tables by default. Pass your table object to kable() and it will return the markdown table:

```{r}
penguins |>
  count(species) |>
  knitr::kable()

```

The intermediate markdown produced is:

|species   |   n|
|:---------|---:|
|Adelie    | 151|
|Chinstrap |  68|
|Gentoo    | 123|

Control the alignment of columns (i.e., the position of the colons, :) with the align argument to kable(). For a full example, see Section 10.5.4.

11.3.1.1.2 Python

The tabulate() function from the tabulate package can produce markdown tables from a variety of Python data structures.

A general approach to create markdown tables is:

  1. Convert the table to a data type tabulate supports (e.g., a pandas.DataFrame)

  2. Pass the table to tabulate() with tablefmt='pipe'

  3. Wrap the result in Markdown() from IPython.display

For example, to apply this strategy to a summary table created by Polars:

```{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))

```

When executed, this intermediate markdown is produced:

| species   |   len |
|:----------|------:|
| Gentoo    |   123 |
| Adelie    |   151 |
| Chinstrap |    68 |

Control the alignment of columns (i.e., the position of the colons, :) with the colalign argument to tabulate(). For a full example, see Section 10.5.4.

While tabulate() is a useful general approach, you may find simpler ways for your specific situation. For example, you can set the default print style for Polars DataFrames to markdown pipe tables using polars.Config.set_tbl_formatting.

11.3.1.2 HTML

The tables in Figure 11.6 were produced using the gt package in R and the great_tables package in Python. Both packages produce HTML tables by default (for other formats, see Section 11.3.1.3).

For example, Figure 11.12 shows a simplified excerpt from the intermediate markdown for the computational table produced in Figure 11.6 when format: html.

document.html.md
::: {.cell-output-display}

```{=html}
<div id="czabgtycdf" ...>
<style>...</style>
<table class="gt_table" data-quarto-disable-processing="false" data-quarto-bootstrap="false">
  <thead>...</thead>
  <tbody class="gt_table_body">...</tbody>
</table>
</div>
```

:::
document.html.md
::: {.cell-output .cell-output-display execution_count=8}
```{=html}
<div id="jnzyjbmsji" ...>
<style>...</style>
<table class="gt_table" data-quarto-disable-processing="false" data-quarto-bootstrap="false">
  <thead>...</thead>
  <tbody class="gt_table_body">...</tbody>
</table>
</div>
```
::: 
Figure 11.12: Intermediate markdown from the code cells in Figure 11.6. The ... indicate parts omitted for brevity.

Inside the ::: {.cell-output-display} div, you’ll notice the raw HTML block syntax ```{=html}, and the table is created with the HTML tags <table>, <thead> and <tbody>. In other words, the code cell has produced an HTML table.

When producing HTML tables, you’ll often find the package you are using provides its own styling (i.e., inside <style> tags), and ways to customize styling via its own functions. Read the documentation for your chosen package to learn how to customize the appearance of your tables.

11.3.1.3 Other formats

The computational engine tells your code which format you’re rendering to, so a package can choose the right table type to produce. Some packages produce a table in the target format directly. For example, flextable (R) produces a native Word table when the target is docx. Other packages always produce HTML and rely on Quarto to convert it. For example, gt (R) and great_tables (Python) produce HTML tables when the target is typst, and Quarto converts them to Typst tables (Section 13.8.2). Refer to the documentation for your chosen package to see which formats it supports.

11.3.2 Multiple tables

If your code cell produces more than one table, you can give the tables sub-captions by providing an array to tbl-subcap.

For example, Figure 11.13 shows a code cell that produces two tables, with sub-captions provided via tbl-subcap. The rendered output is shown in Figure 11.14. To arrange the tables in the panel, see Section 10.4.1.

```{r}
#| label: tbl-species-count
#| tbl-cap: "Number of penguins sampled from each species in the Palmer Archipelago"
#| tbl-subcap: 
#|   - "Total"
#|   - "By year"

penguins |>
  count(species) |>
  gt()


penguins |>
  count(species, year) |>
  pivot_wider(names_from = year, values_from = n) |>
  gt() |>
  cols_label(
    species = "Species"
  )

```
```{python}
#| label: tbl-species-count
#| tbl-cap: "Number of penguins sampled from each species in the Palmer Archipelago"
#| tbl-subcap: 
#|   - "Total"
#|   - "By year"

(
  pl.DataFrame(penguins)
 .group_by('species')
 .len()
 .pipe(GT)
)


(
  pl.DataFrame(penguins)
 .group_by(['species', 'year'])
 .count()
 .pivot(index='species', columns='year', values='count')
 .pipe(GT)
 .cols_label(
     species="Species"
 )
)

```
Figure 11.13: An example of a code cell that produces two tables. Individual table captions are provided as an array to tbl-subcap.
Two tables, one above the other. Each table has a caption prefaced by '(a)' and '(b)' respectively. The overall caption is 'Table 1: Number of penguins sampled from each species in the Palmer Archipelago'.
Figure 11.14: Result of rendering the code cell with multiple tables in Figure 11.13.

When rendered, the tables are placed together in a single “Table” where the overall caption is provided by tbl-cap and prefaced by “Table 1:”. Each individual table in the panel has its own sub-caption prefaced by “(a)” and “(b)”. You can cross-reference the entire panel with the label, e.g., @tbl-species-count, or individual tables by appending an index, e.g., @tbl-species-count-1 and @tbl-species-count-2.

Often the use of tbl-subcap is combined with layout options to arrange the tables in a specific way. For example, the layout-ncol code cell option will arrange the tables in a specified number of columns. Adding the code cell option layout-ncol: 2 to Figure 11.13 would result in the tables laid out side by side rather than one above the other.

Using tbl-subcap is a quick way to make a multi-panel table. But if you want to mix figures and tables, control where each item goes on the page, or caption and cross-reference items in your own way, we recommend one code cell for each output, with the fenced div syntax to label, caption, and arrange them (Section 10.4).

11.4 Troubleshooting

It’s useful to think about the process of getting your figures or tables into the rendered document in three steps:

  1. Execution of the code in your code cell that produces your figure or table.

  2. Translation of the code cell output into markdown, including saving the image file in the case of figures.

  3. Rendering of the markdown to include the figure or table in the final output format.

To troubleshoot a computational figure or table that doesn’t come out looking right, we suggest checking each step in turn. The following sections provide some tips for doing this.

11.4.1 Execute your code interactively

Execute the code cell interactively in your computational environment. Be careful to ensure your local computational environment (interpreter and package versions) matches those used by Quarto. Check that the figure or table looks as you expect. If it doesn’t, you need to fix your code based on the documentation for the packages you are using.

11.4.2 Examine intermediate markdown

The execution engine translates the output of your code cell into markdown. A good way to see what it has done is to examine the intermediate markdown after the engine has finished. Set keep-md: true in your document header:

document.qmd
---
title: My Document
keep-md: true
---

Render your document, and then open the generated markdown file, {filename}.{format}.md. Find the relevant figure or table (e.g., by searching for its label) and examine it carefully. When examining the intermediate markdown, ask yourself:

  • Is the format of the figure or table what you expect?

  • Is the content of the figure or table what you expect? Compare to the result of evaluating your code cells locally. For figures, use the image path in the markdown to find the image file in the {filename}_files/figure-{format}/ folder, and open it directly. For tables, you’ll need to rely on examining the HTML or markdown syntax.

  • Is the surrounding markdown what you expect? For example, are the attributes present on the figure or table markdown? Are the correct classes on the surrounding fenced divs?

Tracking down problems here is tricky because they could be coming from the packages you are using, the engine, or the interaction between the two. Here are some strategies to help you isolate the source of the problem.

11.4.2.1 Explore package options

Some packages are Quarto-aware (or knitr- or jupyter-aware), and will adjust their output based on the context of your document. Other packages aren’t Quarto-aware but provide options that force a format or omit extraneous markup. Check the documentation for your chosen package to see if/how it supports Quarto, and what options are available.

11.4.2.2 Separate code from markdown

Some code cell options, like column and the layout* options, don’t affect how your code produces your figures and tables; instead, they affect the markdown that surrounds them in the document.

If you are using these options, a good first step is to pull apart the layout from the code that produces the figure or table.

Remove the layout options entirely, and check the tables and figures themselves look right. Then, introduce the layout back in, but use the fenced div approach (as outlined in Section 10.4), rather than the code cell options.

11.4.2.3 Do the translation yourself

If you can’t figure out why you aren’t getting the right markdown, you can consider doing the translation yourself. Instead of your code cell producing a figure or table, have it produce the markdown to include the figure or table.

You’ll need to set the code cell option output: asis to tell Quarto not to further process the output of your code cell. Then write code to output text that is the markdown to include your figure or table. For figures, you need to save the image file in your code, and you are responsible for its format, size, and path.

For example, if your code saves an image to a path defined in image_path, Figure 11.15 shows how to produce the markdown to include it.

```{r}
#| echo: false
#| output: asis

cat(paste0("![Caption](", image_path, "){#fig-plot1 fig-alt='Alt text'}\n"))
```
```{python}
#| echo: false
#| output: asis

print(f"![Caption]({image_path}){{#fig-plot1 fig-alt='Alt text'}}\n")
```
Figure 11.15: Code cells that produce markdown to include a figure saved in the path defined in image_path.

11.4.3 Check rendering with a non-computational output

If you see no problems with your intermediate markdown, you should be able to reproduce your problem with a non-computational example. Replace your executable code cells with markdown equivalents. For example, save your figure as an image file, and include it with standard markdown image syntax.

You can use your intermediate markdown as a guide, but simplify as much as you can while still reproducing your problem. You have now eliminated the computational environment as a source of the problem, so it’s possibly a Quarto problem. It’s time to ask for help (Section 18.7.4).

TodoTO-DO

[CVW] Write a Wrap up section once the chapter is reworked into a broader “Computational Outputs” chapter.