Slides with reveal.js

Quarto can also render to revealjs a powerful and convenient presentation format. Slides can make use of all the other features of Quarto, such as inclusion of code, widgets etc.

Examples

Minimal slides

This example shows a minimal set of slides.

Open slides in a new tab

Code
---
title: "Example RevealJS slides"
format:
  revealjs:
    embed-resources: false
    theme: simple
---

## A slide written in Quarto

- Slides are written in `.qmd`
- The output is an HTML RevealJS presentation
- The same syntax works across course pages and slides

## A code example

```{python}
#| echo: true
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2*np.pi, 200)
plt.plot(x, np.sin(x))
plt.show()
```

Advanced slides

This example shows a less minimal deck with fragments, columns, callouts, math, Mermaid diagrams, speaker notes, vertical slides, and executed Python cells.

Open slides in a new tab

Code
---
title: "A richer RevealJS deck"
subtitle: "This is the subtitle"
author: "Course Materials Handbook"
jupyter: python3
format:
  revealjs:
    embed-resources: false
    theme: simple
    width: 1100
    height: 700
    margin: 0.08
    slide-number: true
    progress: true
    hash: true
    transition: fade
    code-line-numbers: true
    preview-links: auto
    navigation-mode: grid
execute:
  echo: true
  warning: false
  message: false
filters:
  - shinylive
---

# Why use slides in the site?

:::: {.columns}

::: {.column width="50%"}
Course slides can live next to the material they support:

::: incremental
- the source is ordinary `.qmd`
- the deck renders to static HTML
- code, diagrams, math, and notes use familiar Quarto syntax
:::
:::

::: {.column width="50%"}
:::{.callout-tip}
The website page can link to the deck, embed it in an iframe, and show the source side by side.
:::
:::

::::

::: notes
Use this slide to explain the workflow rather than the syntax. The point is that slides do not need to be maintained as a separate artifact.
:::

# Fragments

RevealJS can reveal material step by step.

::: incremental
- Start with the idea.
- Add the evidence.
- End with the consequence.
:::

```{.python code-line-numbers="1|3|5"}
temperature = 37
enzyme = "polymerase"
message = f"{enzyme} works near {temperature} C"
print(message)
```

#

:::: {.columns}

::: {.column width="35%"}
### Left column

- compact argument
- short bullets
- good for definitions
:::

::: {.column width="65%"}
### Right column

| Feature | Useful for |
|---|---|
| Columns | comparing ideas |
| Callouts | highlighting warnings |
| Tables | small structured summaries |
| Fragments | staged explanations |
:::

::::

# Math

Quarto supports inline and display math in RevealJS output using LaTeX syntax

$$
P(A \mid B) = \frac{P(B \mid A)P(A)}{P(B)}
$$

```default
$$
P(A \mid B) = \frac{P(B \mid A)P(A)}{P(B)}
$$
```




::: notes
This is a good place to describe the assumptions behind the formula without crowding the slide.
:::

# Diagrams

```{mermaid}
flowchart LR
  A["Write .qmd"] --> B["quarto render"]
  B --> C["RevealJS HTML"]
  B --> D["Website page"]
  C --> E["Embedded deck"]
  D --> E
```

# Executed Python

```{python}
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 200)
signals = {
    "sin(x)": np.sin(x),
    "cos(x)": np.cos(x),
}

fig, ax = plt.subplots(figsize=(7, 3.4))
for label, y in signals.items():
    ax.plot(x, y, label=label)

ax.set_xlabel("x")
ax.set_ylabel("signal")
ax.legend(frameon=False)
ax.grid(alpha=0.25)
plt.show()
```

# Vertical Slides

This is the top slide in a vertical stack.

Press down to move into detail slides, or right to continue the main story.

## Detail: authoring

Vertical slides are useful for optional details:

- backup explanations
- worked derivations
- setup notes
- instructor-only context

## Detail: presenting

Speaker view still works:

- press `S` to open speaker view
- use notes for prompts
- keep the visible slide uncluttered

::: notes
The exact keyboard shortcuts are RevealJS behavior. Quarto passes speaker notes through to RevealJS.
:::

# Images and Figures

Quarto figure syntax works in slides too.

![](https://upload.wikimedia.org/wikipedia/commons/4/4c/DNA_Structure%2BKey%2BLabelled.pn_NoBB.png){fig-align="center"}

```default
![](https://upload.wikimedia.org/wikipedia/commons/4/4c/DNA_Structure%2BKey%2BLabelled.pn_NoBB.png){fig-align="center"}
```

# Interactivity 

Slides can use the interactive elements that Quarto offers. 

```{shinylive-python}
#| standalone: true
#| viewerHeight: 520

from shiny import App, reactive, render, ui
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap, Normalize


app_ui = ui.page_fluid(
    ui.layout_sidebar(
        ui.sidebar(
            ui.input_slider(
                "population_size",
                "Population size",
                min=20,
                max=500,
                value=100,
                step=10,
            ),
            ui.input_slider(
                "starting_frequency",
                "Starting frequency",
                min=0.05,
                max=0.95,
                value=0.5,
                step=0.05,
            ),
            ui.input_slider(
                "generations",
                "Generations",
                min=10,
                max=200,
                value=50,
                step=10,
            ),
            ui.input_slider(
                "replicates",
                "Simulated populations",
                min=1,
                max=50,
                value=20,
                step=1,
            ),
            ui.input_action_button("resimulate", "Resimulate"),
        ),
        ui.output_plot("plot"),
        ui.output_text_verbatim("summary"),
    ),
)


def simulate_drift(population_size, starting_frequency, generations, replicates, seed):
    rng = np.random.default_rng(seed)
    frequencies = np.zeros((replicates, generations + 1))
    frequencies[:, 0] = starting_frequency

    for generation in range(1, generations + 1):
        previous = frequencies[:, generation - 1]
        variant_counts = rng.binomial(population_size, previous)
        frequencies[:, generation] = variant_counts / population_size

    return frequencies


def server(input, output, session):
    @reactive.calc
    def trajectories():
        return simulate_drift(
            population_size=input.population_size(),
            starting_frequency=input.starting_frequency(),
            generations=input.generations(),
            replicates=input.replicates(),
            seed=input.resimulate(),
        )

    @output
    @render.plot(alt="Genetic drift trajectories")
    def plot():
        frequencies = trajectories()
        generation_axis = np.arange(input.generations() + 1)
        final_frequencies = frequencies[:, -1]
        frequency_colors = LinearSegmentedColormap.from_list(
            "frequency_colors",
            ["#d95f02", "#acacac", "#1b9e77"],
        )
        norm = Normalize(vmin=0, vmax=1)

        fig, ax = plt.subplots(figsize=(1200, 800))
        for trajectory, final_frequency in zip(frequencies, final_frequencies):
            ax.plot(
                generation_axis,
                trajectory,
                color=frequency_colors(norm(final_frequency)),
                alpha=0.75,
            )
        ax.axhline(
            input.starting_frequency(),
            color="#4d4d4d",
            linestyle="--",
            linewidth=1,
            alpha=0.7,
        )
        ax.set(
            xlabel="Generation",
            ylabel="Variant frequency",
            ylim=(-0.02, 1.02),
            xlim=(0, input.generations()),
        )
        ax.grid(alpha=0.25)
        fig.colorbar(
            plt.cm.ScalarMappable(norm=norm, cmap=frequency_colors),
            ax=ax,
            label="Final variant frequency",
        )

    @output
    @render.text
    def summary():
        final_frequencies = trajectories()[:, -1]
        lost = np.sum(final_frequencies == 0)
        took_over = np.sum(final_frequencies == 1)
        total = input.replicates()

        return (
            f"By the final generation, the variant was lost in {lost} of \n"
            f"{total} simulated populations and took over in {took_over}."
        )


app = App(app_ui, server)
```

# Takeaways

::: incremental
1. Put slide sources in the website project.
2. Render decks as RevealJS HTML.
3. Embed or link to decks from normal website pages.
4. Show source when it helps contributors copy the pattern.
:::

::: notes
End by pointing back to the source tab in the handbook page.
:::

Quarto’s official demo

These are the demo slides shown in the Quarto documentation.

Open slides in a new tab

Technical details