Skip to main content

12  Interactive Teaching Materials and Dashboards

A printed graph can show how a mathematical model behaves for one set of parameters. An interactive graph can invite a learner to change those parameters, predict the consequences, and test a conjecture. The educational value lies not in motion itself but in the reasoning that the interaction supports. This chapter develops that distinction through mathematical and healthcare examples.

12.1 Learning objectives

After completing this chapter, you should be able to distinguish execution environments, design browser-based investigations, build a dashboard, choose between static and server hosting, and evaluate an activity for accessibility and statistical validity.

12.2 Choosing an execution environment

Quarto can execute R or Python during rendering and include the resulting tables and images in a static page. A reader does not need R or Python installed to view those outputs. However, changing a number in the browser does not automatically rerun the original analysis. For that behavior, we need browser-side computation or a connection to a running application.

Approach Computation occurs Hosting requirement
Static R/Python plot At render time Static files
Observable JavaScript (OJS) In the reader’s browser Static files and required assets
JavaScript widget In the reader’s browser Static files and required assets
Conventional Shiny application On an application server Compatible running server

A static site can link to an externally hosted Shiny application, but it cannot itself run a conventional R or Python server. Browser-based alternatives such as Shinylive have different package and resource constraints; evaluate compatibility before choosing them. Never embed confidential patient records in a browser-delivered dataset: a visitor may inspect downloaded assets even if the interface hides them.

12.3 Designing an interactive mathematical investigation

Consider an idealized concentration model \(C(t)=C_0e^{-kt}\), where \(t\) is measured in hours and \(k>0\) has units of inverse hours. This is a hypothetical mathematical model, not a dosing recommendation. The half-life satisfies \(C(t_{1/2})=C_0/2\). Dividing by \(C_0\) and taking logarithms gives

\[t_{1/2}=\frac{\log 2}{k}. \tag{12.1}\]

A useful learning activity asks the learner to predict whether doubling the initial concentration changes the half-life. Then the learner manipulates the initial concentration while keeping the decay constant fixed. Finally, the learner explains the result using Equation 12.1. This sequence connects visual evidence to mathematical reasoning rather than treating the graph as proof.

12.3.1 Observable JavaScript

Observable cells form a reactive dependency graph: a cell that depends on an input is recomputed when that input changes. The following source can be placed in an HTML Quarto document.

```{ojs}
viewof c0 = Inputs.range([20, 100], {value: 80, step: 5, label: "Initial concentration"})
viewof k = Inputs.range([0.06, 0.5], {value: 0.2, step: 0.01, label: "Decay constant"})
halfLife = Math.log(2) / k
curve = Array.from({length: 121}, (_, i) => ({t: i/10, c: c0*Math.exp(-k*i/10)}))
Plot.plot({x: {label: "Time (hours)"}, y: {label: "Concentration", domain: [0, 100]}, marks: [Plot.line(curve, {x: "t", y: "c"})]})
```

The viewof declaration creates an input and exposes its current value. The curve is recomputed from both parameters. Keeping the vertical axis fixed prevents automatic rescaling from obscuring the effect of changing initial concentration. The companion file includes a textual numerical result as well as the plot.

At \(k=0.2\), the half-life is approximately 3.47 hours. Doubling \(k\) halves the half-life; doubling \(C_0\) leaves it unchanged. A reader should explain both findings algebraically.

Decay curves for three hypothetical decay constants, all starting at 80 units per liter.
Figure 12.1: Decay curves for three hypothetical decay constants, all starting at 80 units per liter.

For print and EPUB editions, provide a static figure such as Figure 12.1 and a question that can be answered without JavaScript. Do not make an essential explanation available only through an interactive control.

12.4 Statistical simulation

A simulation can help distinguish a sampling distribution from the distribution of individual observations. Suppose independent observations come from a population with mean 20 and standard deviation 6. The sample mean has standard error \(6/\sqrt{n}\). A simulation can generate repeated samples and compare the spread of their means for different sample sizes.

A browser implementation should make the sample size, number of repetitions, and population model explicit. Use a reproducible pseudorandom seed when comparing scenarios. Changing the seed produces a different realization, not a different theoretical standard error. A histogram of 500 means is an approximation, not a proof of the central limit theorem.

12.4.1 R implementation

set.seed(120)
n <- 25
means <- replicate(500, mean(rnorm(n, mean = 20, sd = 6)))
hist(means, breaks = 20, xlab = "Sample mean", main = "Sampling distribution")
sd(means)
6 / sqrt(n)

12.4.2 Python implementation

import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(120)
n = 25
means = rng.normal(20, 6, size=(500, n)).mean(axis=1)
plt.hist(means, bins=20)
plt.xlabel("Sample mean")
plt.show()
print(means.std(ddof=1), 6 / np.sqrt(n))

The two languages use different random number generators, so their simulated results need not match exactly. Both should approach the theoretical standard error of 1.2 as the number of repetitions increases. The normal population assumption makes the sampling distribution exactly normal in this example; the simulation illustrates its spread rather than establishing normality for arbitrary populations.

12.5 Designing a healthcare dashboard

A dashboard organizes related indicators around a decision or question. Start by identifying the audience and the unit of observation. In our synthetic clinic example, the unit is an appointment, and the primary measure is waiting time in minutes. A useful dashboard reports the number of observed records, missing values, mean and median, and the distribution of waits. It does not hide missingness behind a single average.

Clinic Records Observed Missing Mean wait
A 5 5 0 16
B 6 5 1 12

A difference in descriptive means does not establish that one clinic provides better care. Appointment mix, staffing, time of day, and missing data may affect comparisons. The dashboard should communicate this limitation alongside the indicators.

12.5.1 Quarto dashboard structure

---
title: "Clinic waiting times"
format: dashboard
---

## Row

### Observed appointments

10 observed; 1 missing.

### Mean waiting time

14 minutes among observed appointments.

## Row

### Distribution by clinic

Insert a computational plot here.

The row and card headings define the layout. The companion dashboard uses a Python cell to calculate its indicators and plot the observations from a CSV file. A separate R dashboard provides the same investigation. Render each independently to avoid requiring both languages in one document.

12.5.2 R Shiny and Python Shiny

A server application is appropriate when a reader must run a model that is too expensive or incompatible with browser execution. In R Shiny, reactive expressions depend on inputs and outputs update when those inputs change. Shiny for Python provides a comparable reactive model. The examples supplied with this chapter implement the same half-life calculation in both languages. Run them locally first. For public deployment, choose a compatible application host, configure resource limits, and avoid sending private data to an unapproved service.

12.6 Quizzes and formative feedback

A good quiz tests reasoning, not simply recognition. Ask: If the decay constant doubles while initial concentration stays fixed, what happens to half-life? The correct answer is that it halves. Feedback should explain why using the equation, and incorrect answers should address likely misconceptions. The supplied standalone HTML quiz uses native radio controls and a live feedback region. It requires no server and can be linked from a Quarto book. Such client-side quizzes are suitable for practice, not secure high-stakes assessment, because answers are present in the delivered source.

12.7 Accessibility and publication readiness

Use visible labels for controls, keyboard-operable inputs, meaningful plot captions, and text summaries of changing results. Avoid encoding distinctions only by color. Test at narrow viewport widths and with keyboard navigation. For charts, specify units and explain the denominator. Provide a static alternative for every required activity. A dashboard should display an informative message when a filter returns no observations, rather than displaying zero as if it were an observed mean.

Before deployment, render the complete book, check links and browser console errors, and test the actual hosted page. Quarto HTML books support static hosting, but application hosting is a separate concern. See the Quarto books guide, Observable guide, and dashboard guide.

12.8 Guided practice

  1. Predict the half-life for decay constants 0.1 and 0.4, then use the interactive investigation to verify the predictions. Explain the ratio.
  2. Run the sampling simulation with sample sizes 9, 36, and 144. Compare empirical and theoretical standard errors and explain discrepancies.
  3. Add a median indicator to the clinic dashboard. Explain how the missing observation affects the interpretation.
  4. Test the quiz using only a keyboard. Revise the feedback to address one misconception and provide a print alternative.

12.9 Troubleshooting

Symptom Check
Slider appears but plot does not update Check reactive dependencies and browser console
Dashboard shows stale data Re-render and verify the input file path
Shiny app fails on static hosting Use an application host or browser-compatible alternative
PDF omits an interactive activity Supply a static figure and equivalent question
Mean is undefined after filtering Check observed count and display a no-data message

12.10 Designing interactions around mathematical reasoning

An interactive lesson should specify what a student is expected to notice, explain, and transfer to a new problem. Begin with a prediction that can be recorded before the control is moved. Next, vary one quantity while holding other quantities constant. Ask for a mathematical explanation, not merely a description of the screen. Finally, present a transfer question that changes the context or representation. For example, a student who recognizes a steeper decay curve should also be able to explain why the half-life is inversely proportional to the decay constant.

A useful design worksheet contains five fields: learning objective, controllable parameter, invariant, feedback, and transfer task. The invariant is particularly important: if every visual feature changes simultaneously, learners may attribute the result to the wrong variable. A fixed axis and a clearly identified reference curve support comparisons. A reset control makes it possible to repeat the investigation without remembering the original settings. Choose slider increments that reveal meaningful mathematical differences rather than implying unrealistic measurement precision.

Distinguish formative feedback from assessment evidence. A browser quiz can immediately explain why a distractor is incorrect, but its answers are visible in the delivered source. It should not be used as a secure examination. An instructor can instead ask students to submit a written prediction, screenshot of a chosen scenario, and explanation of the mathematical principle. The explanation is stronger evidence of understanding than a screenshot alone.

12.11 Calculus laboratory: local linearity and error

Consider the model \(C(t)=80e^{-0.2t}\). At a point \(a\), its tangent approximation is

\[L_a(t)=80e^{-0.2a}[1-0.2(t-a)]. \tag{12.2}\]

The second derivative is positive, so the tangent lies below the curve. The signed error \(E(t)=C(t)-L_a(t)\) is nonnegative. Taylor’s theorem gives \(E(t)=C''(\xi)(t-a)^2/2\) for some \(\xi\) between \(a\) and \(t\). This explains why halving a sufficiently small displacement approximately quarters the error. The statement is local: it does not mean that every pair of displacements produces exactly a factor of four.

Ask students to set \(a=2\), predict the sign of the error at \(t=3\), and then calculate it. The exact concentration is 43.9049, the tangent approximation is 42.9005, and the error is approximately 1.0044. Compare displacements of 1, 0.5, and 0.25 hours. A plot of error against displacement should show the increasing importance of curvature away from the expansion point. The browser laboratory uses two inputs, one for the point of tangency and one for the evaluation point. Both the graph and the numerical summary depend on those inputs.

A decreasing convex curve lies above its tangent except at the point of contact.
Figure 12.2: Exponential curve and tangent at two hours, with approximation error at three hours.

12.11.1 R implementation

C <- function(t) 80 * exp(-0.2*t)
a <- 2
L <- function(t) C(a)*(1-0.2*(t-a))
h <- c(1, 0.5, 0.25)
data.frame(h=h, error=C(a+h)-L(a+h))

12.11.2 Python implementation

import numpy as np

def C(t):
    return 80*np.exp(-0.2*t)
a = 2
h = np.array([1, .5, .25])
error = C(a+h)-C(a)*(1-.2*h)
print(np.column_stack((h,error)))

For print readers, use Figure 12.2 and calculate the three errors by hand or with a calculator. The learning objective remains the same even though the manipulation is no longer live.

12.12 Linear algebra laboratory: transforming a unit square

A matrix is both an array of numbers and a representation of a linear transformation. Consider the family

\[A_s=\begin{bmatrix}1&s\\0&1\end{bmatrix}.\]

For a vector \((x,y)\), the transformed vector is \((x+sy,y)\). The horizontal shear changes the shape of the unit square but preserves its area because \(\det A_s=1\). The lower edge is fixed; the upper edge shifts horizontally by \(s\). The transformation is invertible for every real \(s\), with inverse \(A_{-s}\). These facts are more informative than simply observing that a square becomes a parallelogram.

Use the browser slider to vary \(s\) between -2 and 2. Predict the image of the point \((0,1)\) before moving the control. At \(s=1.5\), the four vertices in order are \((0,0),(1,0),(2.5,1),(1.5,1)\). The area is still one square unit. Ask whether the length of the vertical edge is preserved: its image has length \(\sqrt{1+s^2}\), so the answer is generally no. Area preservation does not imply preservation of distance or angle.

A unit square and a slanted parallelogram share the same horizontal base and height.
Figure 12.3: Unit square and its image under a horizontal shear with parameter 1.5.

12.12.1 R implementation

s <- 1.5
A <- matrix(c(1,s,0,1), nrow=2, byrow=TRUE)
V <- rbind(c(0,1,1,0), c(0,0,1,1))
A %*% V
det(A)

12.12.2 Python implementation

import numpy as np
s = 1.5
A = np.array([[1,s],[0,1]])
V = np.array([[0,1,1,0],[0,0,1,1]])
print(A @ V)
print(np.linalg.det(A))

Use a fixed aspect ratio so that equal coordinate distances appear equal on the screen. Without that constraint, the plot may distort the apparent angle or shape. An accessible numerical alternative lists the transformed vertices and determinant alongside the picture.

12.13 Probability laboratory: separating model parameters from simulation settings

For independent normal observations with mean 20 and standard deviation 6, the sample mean is exactly normal with standard deviation \(6/\sqrt{n}\). The theoretical probability of a sample mean above 22 is \(1-\Phi(\sqrt{n}/3)\). Increasing \(n\) reduces this probability because the threshold is above the population mean. At \(n=9\), the probability is approximately 0.1587; at \(n=36\), it is approximately 0.02275. The threshold is a hypothetical teaching benchmark, not a clinical decision rule.

A useful extension is to compare the theoretical probability with the fraction of simulated sample means above 22. The number of repetitions controls Monte Carlo variability, not the theoretical standard error. With \(B\) independent repetitions, the Monte Carlo standard error of an estimated probability \(\hat p\) is approximately \(\sqrt{\hat p(1-\hat p)/B}\). When no simulated event occurs, this plug-in estimate is zero, but that does not prove the true probability is zero. Increase the repetition count or use an appropriate interval for a binomial proportion.

For browser activities, a seeded simulation can make a lesson repeatable. Avoid reseeding on every observation within a sample. Document whether changing the sample size regenerates all observations or reuses a nested sequence. Either choice can be appropriate, but the comparison should be described. For a static alternative, provide a table of theoretical probabilities and a fixed simulation realization with its seed.

12.14 Dashboard laboratory: thresholds, denominators, and empty selections

The synthetic clinic dataset contains eleven appointments, ten observed waits, and one missing wait. For a selected clinic and threshold \(q\), define the indicator \(I(w>q)\) only for observed waiting times. The exceedance fraction is the count above the threshold divided by the number of observed waits, not the total number of appointments. A missing wait is not a zero-minute wait and is not evidence that the threshold was met.

At a strict threshold of 15 minutes, Clinic A has two exceedances among five observed waits, and Clinic B has one among five. The pooled fraction is 3/10, or 30 percent. If the threshold changes to an inclusive comparison, Clinic A has three exceedances, so the pooled fraction becomes 4/10. The difference illustrates why a dashboard must disclose its comparison operator. A threshold should be selected for a stated purpose, not tuned until a desired comparison appears.

A useful dashboard reports the selected group, total appointments, observed waits, missing waits, mean, median, threshold, numerator, and denominator. Display the observed fraction alongside the missing count. When no records match the selected clinic, return a clear no-data state. When records exist but all waits are missing, report the total and missing count while leaving the mean and fraction undefined. A genuine zero exceedance fraction is different from either case.

The extended laboratory contains a static Quarto dashboard and a browser-based interactive lesson. The former demonstrates the dashboard layout with computed summaries; the latter allows the reader to change the threshold and group without rerendering. This separation avoids implying that a render-time Python cell automatically responds to a browser input.

12.14.1 R implementation

clinic <- read.csv('clinic.csv')
w <- clinic$wait_min[clinic$clinic == 'A']
observed <- w[!is.na(w)]
if (length(observed)) {
  c(total=length(w), observed=length(observed),
    missing=sum(is.na(w)), mean=mean(observed),
    above=sum(observed>15), fraction=mean(observed>15))
}

12.14.2 Python implementation

import pandas as pd
clinic = pd.read_csv('clinic.csv')
w = clinic.loc[clinic.clinic.eq('A'),'wait_min']
observed = w.dropna()
print({'total':len(w), 'observed':len(observed),
       'missing':int(w.isna().sum()),
       'mean':observed.mean(),
       'above':int((observed>15).sum()),
       'fraction':(observed>15).mean()})

12.15 Choosing an application architecture

For a textbook with thousands of readers, browser-side computation can avoid maintaining a server for each session. OJS is suitable for moderate mathematical computations, interactive plots, and public teaching datasets. A conventional Shiny application is appropriate when the calculation needs an R or Python package that cannot run in the browser, when server-side authorization is needed, or when computation must access protected resources. The latter case also requires institutional security review; a server framework by itself does not establish privacy compliance.

Design the application around a pure calculation function that accepts inputs and returns results. Keep the display code separate. This makes it possible to test the same mathematical cases independently of the interface. For example, the threshold function should return a null fraction when no observed values exist. A test can verify this without opening a browser. Shiny reactive expressions and OJS cells can call such functions, but their syntax and deployment requirements differ. The original Shiny examples in this chapter provide starting points for both languages.

12.16 Accessibility, performance, and release laboratory

Test the interaction using a keyboard before using a mouse. A reader should be able to reach each input, understand its label and current value, and obtain a textual result. Use a visible focus indicator and avoid relying on red versus green alone. Include a numerical summary and meaningful graph description. Do not announce every intermediate slider movement in a live region if it makes assistive technology unusable; test the actual experience.

For a printed edition, replace each essential interactive investigation with a static figure, a table of selected parameter values, and a question that targets the same objective. In Quarto, format-specific content blocks can distinguish HTML from non-HTML outputs. Verify the actual rendered PDF and EPUB rather than assuming the browser widget will be preserved. A static alternative should not merely tell the reader to visit a website.

A release checklist should include initial values, boundary values, invalid inputs, empty selections, keyboard navigation, narrow screens, offline behavior, and the actual deployed URL. Test numerical outputs against an independently calculated benchmark. Check that the browser does not download private data, credentials, or answer keys intended for a secure assessment. Document external JavaScript dependencies and test what happens when they cannot load. The companion standalone HTML lesson uses no external libraries, so its numerical controls can also be tested offline. Its Quarto OJS counterpart requires the usual Quarto-generated assets.

12.17 Extended guided practice

  1. Calculate the tangent error at displacements 1, 0.5 and 0.25 from \(a=2\). Compare successive ratios.
  2. Explain why the tangent error is nonnegative using convexity.
  3. Transform the unit square for \(s=-1\) and identify the inverse transformation.
  4. Show algebraically why a shear preserves area but not all distances.
  5. Calculate the normal sampling probability above 22 for \(n=9\) and \(n=36\).
  6. Explain why increasing simulation repetitions does not change the theoretical probability.
  7. Calculate the pooled strict and inclusive exceedance fractions at 15 minutes.
  8. Distinguish a zero exceedance fraction from a no-data selection.
  9. Propose an accessible print alternative for the shear activity.
  10. Choose a hosting architecture for a public lesson and justify why a conventional Shiny server is or is not needed.

12.18 Extended project: an interactive learning portfolio

Develop three connected learning investigations: a calculus approximation, a linear transformation, and a statistical dashboard. Each must have a prediction prompt, a controlled input, a numerical benchmark, a mathematical explanation, and a transfer question. Supply a static alternative, a formative feedback item, a documented test of boundary conditions, and a deployment plan. Use only synthetic or appropriately public data. Ask a peer to complete one activity using keyboard navigation and record the findings rather than claiming accessibility without evidence.

Criterion Points
Mathematical and statistical correctness 8
Meaningful interaction and feedback 6
Dashboard denominators and no-data behavior 5
Accessible static alternatives 5
Reproducibility, testing and hosting documentation 6
Total 30

12.19 Chapter summary

Interactive publishing connects a learner’s actions to meaningful mathematical or statistical feedback. Browser-based computation is a practical choice for static online books; server-based applications require additional infrastructure. Dashboards should expose denominators and uncertainty, and all essential instructional content should have accessible alternatives.

12.20 Review exercises

  1. Distinguish render-time and browser-time computation.
  2. Explain why static hosting cannot run a conventional Shiny server.
  3. Define a reactive dependency.
  4. Explain the purpose of viewof.
  5. Calculate half-life for \(k=0.25\).
  6. Explain why initial concentration does not affect half-life.
  7. Find the theoretical standard error for \(n=36\).
  8. Explain why simulations in R and Python differ.
  9. Distinguish sample size from number of repetitions.
  10. Explain why a fixed axis can help comparison.
  11. Calculate the missing fraction for Clinic B.
  12. Explain why a descriptive dashboard cannot establish causality.
  13. Describe an accessible alternative to a color-only legend.
  14. Explain why a client-side quiz is unsuitable for secure exams.
  15. Describe a no-data state.
  16. List three deployment checks.

12.21 Applied project

Develop an interactive health-science learning module containing a mathematical investigation, a dashboard using synthetic data, and a formative quiz. Include a static alternative, source files, instructions for rendering, and a short explanation of hosting requirements. Evaluate the module with a peer before release.

Criterion Points
Mathematical and statistical correctness 6
Meaningful interaction and feedback 5
Dashboard clarity and interpretation 5
Accessibility and static alternative 4
Reproducibility and deployment documentation 5
Total 25

12.22 Integrated browser laboratory

Open the quantitative learning laboratory to explore exponential decay, seeded sampling distributions, threshold definitions and formative feedback. The laboratory uses local JavaScript and does not require a server or transmit student responses.

For all editions, predict the effect of doubling the decay constant, quadrupling sample size, and including equality in a threshold. Then verify the predictions: at \(k=0.2\), \(C(5)=29.4304\) and half-life is 3.4657 hours; at \(k=0.4\), the corresponding values are 10.8268 and 1.7329 hours. For population SD 6, sample sizes 25 and 100 yield standard errors 1.2 and 0.6. For waits 10, 12, 15, 18, 25 and one missing value, strict and inclusive thresholds at 15 yield 2/5 and 3/5. The missing observation is excluded from the observed denominator and reported separately.

The simulation uses a fixed pseudorandom seed and Box–Muller normal draws for repeatable browser results. Its histogram uses a fixed horizontal range and reports observations outside that range; vertical scaling changes with the maximum bin count. It is an instructional simulation, not a cryptographic random generator. Compare theoretical and simulated standard errors rather than expecting exact equality.

12.23 Further reading

12.24 Supplemental assessment

  1. Conceptual (4 points). Distinguish client-side computation from server-side execution.
  2. Technical (8 points). For X normal with mean 20 and SD 6, calculate standard errors for n=9,36,100.
  3. Applied (8 points). Build a slider investigation with a static worksheet and a prediction question.

See the student assessment packet in the source package for submission guidance and any required datasets.

12.25 Looking ahead

Unify the appearance of these resources using themes and templates in Chapter 13.

12.26 Interactive learning lab

Explore the activity below, then explain what changed and why.

Open the activity in its own page.