Module 2 Advanced Literate Programming with Quarto

Advanced Codebook

Author

Jae Jung

Published

February 9, 2025

1 Overview

1.1 Learning outcomes

  1. Describe the various authoring tools you can implement to make your Quarto document effective.
  2. Describe the various computational options you can implement on Quarto documents.

1.2 The textbook chapters to cover:

2 Quarto Authoring

2.1 Tables

  • Using source mode
Right Left Default Center
12 12 12 12
123 123 123 123
1 1 1 1


  • Using visual mode
MSDM Program Curriculum1
Digital Marketing Strategy Emphasis Marketing Analytics Emphasis
Major Required 20 units 20 units
Major Electives 14 units 14 units
Emphasis Recommended 10 units 10 units
Emphasis Other 4 units 4 units
Total Units 34 units 34 units

2.2 Citations

2.3 References

  • Automatically created at the end of the document.

2.4 Cross References

  • Provides numbered references and hyperlinks to figures, tables, equations, and sections.
Types of Referenceable Elements
Elements ID How to Cite
Figures2 #fig-xxx @fig-xxx
Tables #tbl-xxx @tbl-xxx
Equations #eq-xxx @eq-xxx
Sections #sec-xxx @sec-xxx
  • Cross-reference-able entities generally require a label (unique identifier) and a caption.

Here is an example of cross-referencing to an equation: we can fit a simple linear regression model of the form shown in Equation 1.

2.5 Footnote

  • An example of foot note is provided in Section 2.4.
  • Footnotes in a document should be unique3

2.5.1 Inlines Footnote

Here is an inline note.4

2.6 Aside

aside utilizes divs and puts the note to the right margin.

If you want to master the literate coding, you should be patient in your progress. Try using Quarto everyday for your work. For the first couple of days, you may be slow, but it will become a second nature sooner or later.

2.7 Divs and Spans

You can add classes, attributes, and other identifiers to regions of content using Divs and Spans (you’ll see an example of this below in Section 2.8).

2.7.1 Divs

For example, here we add the “border” class to a region of content using a div (:::):

::: {.border} 
This content can be styled with a border 
:::

Once rendered to HTML, Quarto will translate the markdown into:

<div class="border">   
  <p>This content can be styled with a border</p> 
</div>

An example of two column layout with penguins data is provided in Section 2.13.

2.7.2 Spans

A bracketed sequence of inlines, as one would use to begin a link, will be treated as a Span with attributes if it is followed immediately by attributes:

[This is *some text*]{.class key="val"}

Once rendered to HTML, Quarto will translate the markdown into

<span class="class" data-key="val">
  This is <em>some text</em>
</span>

2.8 Callout Blocks

Note
  • Callouts are markdown divs that have special callout attributes.
Important
  • We can insert a callout using the Insert Anything tool.

2.9 Other Blocks

2.10 Code Annotation

2.10.1 Annotation Syntax

Annotations for a code cell consist of two related elements:

  1. Each annotated line should be terminated with a comment (using the code cell’s language comment character) followed by a space and then an annotation number enclosed in angle brackets (e.g. # <2>). You may repeat an annotation number if the annotation spans multiple lines.

  2. An ordered list that appears immediately after the code cell which includes the contents of each annotation. Each numbered item in the ordered list will correspond to the line(s) of code with the same annotation number.

For example, If the annotations are made,

```r
library(tidyverse)
library(palmerpenguins)
penguins |>                                      # <1>
  mutate(                                        # <2>
    bill_ratio = bill_depth_mm / bill_length_mm, # <2>
    bill_area  = bill_depth_mm * bill_length_mm  # <2>
  )                                              # <2>
```
1. Take `penguins`, and then,
2. add new columns for the bill ratio and bill area.

we will have the following rendered in the document.

```{r}
#| code-fold: false

library(tidyverse)
library(palmerpenguins)
penguins |>
  mutate(
    bill_ratio = bill_depth_mm / bill_length_mm,
    bill_area  = bill_depth_mm * bill_length_mm
  )
```
1
Take penguins and then,
2
add new columns for the bill ratio and bill area.
# A tibble: 344 × 10
   species island    bill_length_mm bill_depth_mm flipper_length_mm body_mass_g
   <fct>   <fct>              <dbl>         <dbl>             <int>       <int>
 1 Adelie  Torgersen           39.1          18.7               181        3750
 2 Adelie  Torgersen           39.5          17.4               186        3800
 3 Adelie  Torgersen           40.3          18                 195        3250
 4 Adelie  Torgersen           NA            NA                  NA          NA
 5 Adelie  Torgersen           36.7          19.3               193        3450
 6 Adelie  Torgersen           39.3          20.6               190        3650
 7 Adelie  Torgersen           38.9          17.8               181        3625
 8 Adelie  Torgersen           39.2          19.6               195        4675
 9 Adelie  Torgersen           34.1          18.1               193        3475
10 Adelie  Torgersen           42            20.2               190        4250
# ℹ 334 more rows
# ℹ 4 more variables: sex <fct>, year <int>, bill_ratio <dbl>, bill_area <dbl>

2.10.2 Annotation Style

below

By default (or if code-annotations: below is specified), code annotation text will appear below the code cell.

hover

Code annotation text will be displayed when the user hovers over the annotation marker for a line of code (if code-annotations: hover is specified)).

select

If code-annotations: select is specified, code annotation text will be displayed when the user clicks on an annotation marker (selecting it). The annotation text can be dismissed by clicking the annotation marker once again.

2.11 Article Layout

  • We can use the column: page-right cell option to indicate we would like our figure to occupy the full width of the screen, with some inset.
  • See the documentation on Article Layout for additional details.
  • An illustration is given in Figure 4.

2.12 Videos

2.13 Columns

Figure 1: Penguin Species Drawing by Allison Horst
Figure 2: Explaining Bill Dimensions

The average bill length is 43.99 mm and he average bill depth is 17.16 mm.

The data was collected between 2007 and 2009.

2.14 Figures

# A tibble: 234 × 11
   manufacturer model      displ  year   cyl trans drv     cty   hwy fl    class
   <chr>        <chr>      <dbl> <int> <int> <chr> <chr> <int> <int> <chr> <chr>
 1 audi         a4           1.8  1999     4 auto… f        18    29 p     comp…
 2 audi         a4           1.8  1999     4 manu… f        21    29 p     comp…
 3 audi         a4           2    2008     4 manu… f        20    31 p     comp…
 4 audi         a4           2    2008     4 auto… f        21    30 p     comp…
 5 audi         a4           2.8  1999     6 auto… f        16    26 p     comp…
 6 audi         a4           2.8  1999     6 manu… f        18    26 p     comp…
 7 audi         a4           3.1  2008     6 auto… f        18    27 p     comp…
 8 audi         a4 quattro   1.8  1999     4 manu… 4        18    26 p     comp…
 9 audi         a4 quattro   1.8  1999     4 auto… 4        16    25 p     comp…
10 audi         a4 quattro   2    2008     4 manu… 4        20    28 p     comp…
# ℹ 224 more rows
Show the code
```{r}
#| label: fig-scatterplot
#| fig-cap: "City and highway mileage for 38 popular models of cars."
#| fig-alt: "Scatterplot of city vs. highway mileage for cars, where points are colored by the number of cylinders. The plot displays a positive, linear, and strong relationship between city and highway mileage, and mileage increases as the number of cylinders decreases."
#| fig-width: 6
#| fig-height: 3.5
#| code-line-numbers: true

ggplot(mpg, aes(x = hwy, y = cty, color = cyl)) +
  geom_point(alpha = 0.5, size = 2) +
  scale_color_viridis_c() +
  theme_minimal()
```
Scatterplot of city vs. highway mileage for cars, where points are colored by the number of cylinders. The plot displays a positive, linear, and strong relationship between city and highway mileage, and mileage increases as the number of cylinders decreases.
Figure 3: City and highway mileage for 38 popular models of cars.
Update

Figure 3 shows a positive, strong, and linear relationship between the city and highway mileage.

2.15 Multiple Figures

The plots in Figure 4 show the relationship between city and highway mileage for 38 popular models of cars. In Figure 4 (a) the points are colored by the number of cylinders while in Figure 4 (b) the points are colored by engine displacement.

Show the code
```{r}
#| label: fig-mpg
#| fig-cap: "City and highway mileage for 38 popular models of cars."
#| fig-subcap:
#|   - "Color by number of cylinders"
#|   - "Color by engine displacement, in liters"
#| layout-ncol: 2
#| column: page-right

ggplot(mpg, aes(x = hwy, y = cty, color = cyl)) +
  geom_point(alpha = 0.5, size = 2) +
  scale_color_viridis_c() +
  theme_minimal()

ggplot(mpg, aes(x = hwy, y = cty, color = displ)) +
  geom_point(alpha = 0.5, size = 2) +
  scale_color_viridis_c(option = "E") +
  theme_minimal()
```
(a) Color by number of cylinders
(b) Color by engine displacement, in liters
Figure 4: City and highway mileage for 38 popular models of cars.
Tip

If you have 3, 4, or more figures in a panel there are many options available for customizing their layout. See the article Figure Layout for details.

2.16 Data Frames

---
title: "Document"
format: 
   html:
     df-print: paged
---

3 HTML Basics

3.1 Table of Contents

test section

3.1.1 toc-depth

Default

Default is 3

---
toc: true
toc-depth: 3
---

3.2 toc-expand

  • Options
    • true
    • false
    • number (e.g., 2)
---
toc: true
toc-expand: 2
---

3.3 toc-location

  • Options
    • right (default)
    • left
    • body
    • right-body
    • left-body
format:
  html:
    toc: true
    toc-location: right-body

3.4 Section Numbering

  • Default is all levels
  • To exclude an individual heading from numbering add .unnumbered class to it as in Section 3.1.1
---
number-sections: true
number-depth: 3
---

3.6 LaTex Equations

3.6.1 Display equations

\[ Sales = \hat{\beta}_0 + \hat{\beta}_1 \times Ads + \epsilon \tag{1}\]

3.6.2 inline equations

  • The relationship between ads spending and sales may be captured in this regression: \(Sales = \hat{\beta}_0 + \hat{\beta}_1 \times Ads + \epsilon\)

3.7 Tabset and Tabset Groups

fizz_buzz <- function(fbnums = 1:50) {
  output <- dplyr::case_when(
    fbnums %% 15 == 0 ~ "FizzBuzz",
    fbnums %% 3 == 0 ~ "Fizz",
    fbnums %% 5 == 0 ~ "Buzz",
    TRUE ~ as.character(fbnums)
  )
  print(output)
}
def fizz_buzz(num):
  if num % 15 == 0:
    print("FizzBuzz")
  elif num % 5 == 0:
    print("Buzz")
  elif num % 3 == 0:
    print("Fizz")
  else:
    print(num)
  • Tabs within a group are all switched together.

Tab content for R will be here.

Tab content for Python will be here.

3.8 Self Contained

You might alternatively want to create an entirely self-contained HTML document (with images, CSS style sheets, JavaScript, etc. embedded into the HTML file). You can do this by specifying the embed-resources option:

format:
  html:
    embed-resources: true

3.9 Anchor Sections

Hover over a section title to see an anchor link.

format:
  html:
    anchor-sections: true

3.10 Smooth-scrolling

Enable smooth scrolling within the page

format:
  html:
    smooth-scroll: true

3.12 Lists

4 HTML Code Blocks

4.1 Hiding Code

4.1.1 Unexcuted Blocks

  • Double curly brackets.
  • printed as only one curly bracket
```{python}
1 + 1
```
  • Use of four back ticks
---
title: "My document"
---

Some markdown content.

```{python}
1 + 1
```

Some additional markdown content.

4.2 Foding Code

4.2.1 Options

Value Behavior
false No folding (default)
true Fold code
show Fold code (initially shown)

4.2.2 Type of Implementation

It can be implemented globally and locally

  1. Globally at the Yaml header

    ---
    title: "Quarto Computations"
    format:
      html:
        code-fold: true
        code-summary: "Show the code"
    ---
  2. Locally at the code chunk

```{r}
#| code-fold: true
#| code-summary: "Show the code"
```

4.3 Code Overflow

The default is scroll

4.3.1 global setting

format:
  html:
    code-overflow: wrap

4.3.2 code block setting

```{python}
#| code-overflow: wrap

# very long line of code....
```

4.3.3 Static code block setting

For a static code block, add the .code-overflow-wrap CSS class:

```{.python .code-overflow-wrap}
# very long line of code....
```

4.4 Code Tools

Control it at the yaml only.

4.4.1 Default setting

format:
  html:
    code-fold: true
    code-tools: true

The above setting will results in the code tool icon appearing, right to the main header of the rendered HTML file: A screen shot of the header of a rendered Quarto document showing the result of setting both the code-fold and code-tools option to true. There is a drop-down menu labeled 'Code' to the right of the page title with a triangle pointing down. The menu is open and there are three options listed vertically beneath it: 'Hide All Code,' 'Show All Code,' and 'View Source.'

4.4.2 Sub-options of code-tools

format:
  html: 
    code-tools:
      source: true
      toggle: false
      caption: none

4.5 Appearance

By default code blocks are rendered with a left border whose color is derived from the current theme.

See the yaml area for the current setting.

4.6 Highlighting

  • Example

The highlight-style option determines which theme is used. For example:

highlight-style: github

These themes are “adaptive.” These are designed to work well with sites that include a dark and light mode.

  • a11y
  • arrow
  • atom-one
  • ayu
  • breeze
  • github
  • gruvbox

All of the standard Pandoc themes are also available:

  • pygments
  • tango
  • espresso
  • zenburn
  • kate
  • monochrome
  • breezedark
  • haddock

As well as an additional set of extended themes, including:

  • dracula
  • monokai
  • nord
  • oblivion
  • printing
  • radical
  • solarized
  • vim-dark

4.7 Line Numbers

In this document, code line numbers can be seen Figure 3.

4.8 Code Linking

  • enables hyper-linking of functions within code blocks to their online documentation.

    ---
    title: "Quarto Computations"
    format:
      html:
        code-link: true
    ---

4.9 Inline Code

There are 234 observations in our data.

The average city mileage of the cars in our data is 16.86 and the average highway mileage is 23.44.

4.10 Caching

5 HTML Theming

5.1 Overview

Quarto uses Bootstrap 5 by default for HTML, but there are other themes possible.

theme: default # bootstrap 5 default
theme: cosmo   # cosmo bootswatch theme
theme: pandoc  # pandoc default html treatment
theme: none    # no theme css added to document

To change the theme, modify yaml header.

format:
  html:
    theme: united

5.2 Basic Options

  • Bootstrap or the Pandoc theme
Option Description
max-width The maximum width occupied by page content. Defaults to 1400px for bootstrap themes and 36em for the pandoc theme.
mainfont Sets the font-family property for the document.
fontsize Sets the base CSS font-size for the document.
fontcolor Sets the default text color for the document.
linkcolor Sets the default text color for hyperlinks.
monofont Sets the font-family property for <code> elements.
monobackgroundcolor Sets the background-color property for <code> elements.
linestretch Sets the CSS line-height property (affects distance between lines of text, defaults to 1.5).
backgroundcolor Sets the background-color for the document.
margin-left, margin-right, margin-top, margin-bottom Sets the CSS margin properties for the document body.
  • Yaml setting
    • The default line height is 1.5

    • If we want to set the font-size a bit larger and specify that we want a bit more space between lines of text:

      title: "My Document"
      format:
        html: 
          theme: cosmo
          fontsize: 1.1em
          linestretch: 1.7

5.3 Theme Options

Sass theme files can define both variables that globally set things like colors and fonts, as well as rules that define more fine grained behavior. To customize an existing Bootstrap theme with your own set of variables and/or rules, just provide the base theme and then your custom theme file(s):

theme:
  - cosmo
  - custom.scss

The scss file consists of the follwoing two sections:

  • Variable section
    • /*-- scss:defaults --*/
  • Rules section
    • /*-- scss:rules --*/

Here is an example of custom.scss file

/*-- scss:defaults --*/
$h2-font-size:          1.6rem !default;
$headings-font-weight:  500 !default;

/*-- scss:rules --*/
h1, h2, h3, h4, h5, h6 {
  text-shadow: -1px -1px 0 rgba(0, 0, 0, .3);
}

5.4 Custom Themes

You can also use a completely customized theme of your own as in

theme: custom.scss

5.5 Dark Mode

  • You may also provide a light and dark theme.
  • Quarto will automatically create a toggle to allow your reader to select the desired dark or light appearance.
  • The toggle will automatically appear in the top right corner of your html output.

For example:

theme:
  light: faltly
  dark: darkly

5.5.1 Customizing Themes

  • You may provide a custom theme for dark and light mode, or a list of scss files to customize the light and dark appearance.
  • For example uses the following to use a light cosmo theme and then customizes the cosmo theme with additional Sass variables when in dark mode:
theme:
  light: cosmo
  dark: [cosmo, theme-dark.scss]

5.6 Sass Variables

The Sass Variables can be specified within SCSS files (note that these variables should always be prefixed with a $ and are specified within theme files rather than within YAML options):

5.7 Sass Variables

The following Sass Variables can be specified within SCSS files (note that these variables should always be prefixed with a $ and are specified within theme files rather than within YAML options):

5.7.1 Colors

Variable Notes
$body-bg The page background color.
$body-color The page text color.
$link-color The link color.
$input-bg The background color for HTML inputs.
$popover-bg The background color for popovers (for example, when a citation preview is shown).

5.7.2 Fonts

Variable Notes
$font-family-sans-serif The sans-serif font family for the page.
$font-family-monospace The monospace font family for the page.
$font-size-root The base font size for the page.
$toc-font-size The font size for the page TOC.

$h1-font-size

$h2-font-size

$h3-font-size

$h4-font-size

$h5-font-size

Font sizes for the specified headings.

5.7.3 Code Blocks

Variable Notes
$code-block-border-left By default, Quarto does not display a left border on code blocks. Set this variable to a truthy value or a CSS color to enable the left border.
$code-block-border-left-style The style of the left border displayed on code blocks. Defaults to solid.
$code-block-border-left-size The thickness of the left border displayed on code blocks. Defaults to 3px;
$code-block-padding-left The amount of padding applied between the code and the border. Defaults to 0.6em.
$code-block-bg By default, Quarto sets a background on code blocks by adding transparency to the theme’s progress-bg color. Set this variable to truthy value or a CSS color.
$code-block-bg-padding The padding applied to the code block. Defaults to 0.4em.
$code-block-bg-alpha The amount to alter the transparency fo the progress-bg color. This is not used if an explicit background color is set. Defaults to -0.35.

5.7.3.1 Code Annotation

You can customize the colors used to highlight lines when code annotation is used:

Variable Notes
$code-annotation-higlight-color The color used as a border on highlighted lines.
$code-annotation-higlight-bg The color used for the background of highlighted lines.

5.7.3.2 Code Copy

You can also customize the colors of the button which appears for code-copy: true with the following variables:

Variable Notes
$btn-code-copy-color The color used for the copy button at the top right of code blocks.
$btn-code-copy-color-active The hover color used for the copy button at the top right of code blocks.

5.7.4 Inline Code

Variable Notes
$code-bg The background color of inline code. Defaults to a mix between the body-bg and body-color.
$code-color The text color of inline code. Defaults to a generated contrasting color against the code-bg.

5.7.5 Table of Contents

Variable Notes
$toc-color The color for table of contents text.
$toc-font-size The font-size for table of contents text.
$toc-active-border The left border color for the currently active table of contents item.
$toc-inactive-border The left border colors for inactive table of contents items.

5.7.6 Layout

Variable Notes
$content-padding-top Padding that should appear before the main content area (including the sidebar, content, and TOC.

5.7.8 Callouts

Variable Notes
$callout-border-width The left border width of callouts. Defaults to 5px.
$callout-border-scale The border color of callouts computed by shifting the callout color by this amount. Defaults to 0%.
$callout-icon-scale The color of the callout icon computed by shifting the callout color by this amount. Defaults to 10%.
$callout-margin-top The amount of top margin on the callout. Defaults to 1.25rem.
$callout-margin-bottom The amount of bottom margin on the callout. Defaults to 1.25rem.
$callout-color-<type>

The colors for the various types of callouts. Defaults:

type default
note $blue
tip $green
caution $orange
warning $yellow
important $red

5.7.9 Bootstrap Variables

In addition to the above Sass variables, Bootstrap itself supports hundreds of additional variables. You can learn more about Bootstrap’s use of Sass variables or review the raw variables and their default values.

6 Publishing

  • Once your document is rendered to HTML, you can publish to RPubs (a free service from RStudio for sharing documents on the web) simply by clicking the Publish button on the editor toolbar or preview window. Alternatively, you can use the quarto::quarto_publish_doc() function.

    ```{r}
    quarto::quarto_publish_doc(   
      "authoring.qmd",   
      server = "rpubs.com"   
      )
    ```

    6.1 Publish Command

The quarto publish command provides a straightforward way to publish documents to the following: - Quarto Pub - GitHub Pages, - Netlify, and - Posit Connect.

For example, here are the commands to publish document.qmd to each of these services:

Terminal
quarto publish quarto-pub document.qmd
quarto publish gh-pages document.qmd
quarto publish netlify document.qmd
quarto publish connect document.qmd

6.2 Standalone HTML

You can optionally render Quarto documents into self contained HTML, whereby all of the content required to render the article (images generated by plots, required CSS and JavaScript, etc.) are bundled into a single HTML file. Use the embed-resources option to do this:

format:
  html:
    embed-resources: true

Then, you can share this HTML file using the same means you use to share other document types like spreadsheets, presentations, and PDFs (e.g by uploading it to Dropbox or any other file sharing service).

Note that when using embed-resources: true, math libraries like MathJax and KaTeX are not embedded by default because they are quite large and often time consuming to download. If you do want to embed math libraries, add the self-contained-math: true option:

format:
  html:
    embed-resources: true
    self-contained-math: true

7 Resources

References

Knuth, D. E. 1984. “Literate Programming.” The Computer Journal 27 (2): 97–111. https://doi.org/10.1093/comjnl/27.2.97.

Footnotes

  1. This is a table caption added when a table was created in the visual mode.↩︎

  2. Figures can be assigned to charts inside code chunks or the embedded graphics.↩︎

  3. If the footnotes are not unique, readers will be confused.↩︎

  4. Inline notes are easier to write, since you don’t have to pick an identifier and move down to type the note.↩︎