A richer RevealJS deck

This is the subtitle

Course Materials Handbook

Why use slides in the site?

Course slides can live next to the material they support:

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

Tip

The website page can link to the deck, embed it in an iframe, and show the source side by side.

Fragments

RevealJS can reveal material step by step.

  • Start with the idea.
  • Add the evidence.
  • End with the consequence.
temperature = 37
enzyme = "polymerase"
message = f"{enzyme} works near {temperature} C"
print(message)

Left column

  • compact argument
  • short bullets
  • good for definitions

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)} \]

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

Diagrams

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

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

Executed 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

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"}

Interactivity

Slides can use the interactive elements that Quarto offers.

#| '!! shinylive warning !!': |
#|   shinylive does not work in self-contained HTML documents.
#|   Please set `embed-resources: false` in your metadata.
#| 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

  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.