8  Data Science Tools for Reporting

8.1 Documentation and Reporting Tools

This chapter covers the tools for turning an analysis into a document that rebuilds itself from the data, so a corrected figure costs a re-render rather than an afternoon.

8.1.1 Markdown: The Foundation of Documentation

Markdown is a lightweight markup language that’s easy to read and write.

It is what GitHub renders, what Jupyter cells hold, and what Quarto and R Markdown are built on, so it’s worth ten minutes even if you learn nothing else here.

8.1.1.1 Basic Markdown Syntax

# Heading 1
## Heading 2
### Heading 3

**Bold text**
*Italic text*

[Link text](https://example.com)

![Alt text for an image](image.jpg)

- Bullet point 1
- Bullet point 2

1. Numbered item 1
2. Numbered item 2

| Column 1 | Column 2 |
|----------|----------|
| Cell 1   | Cell 2   |

> This is a blockquote

`Inline code`

```python
# Code block
print("Hello, world!")
```

The language name after the opening backticks is optional and only controls syntax highlighting. Later in this chapter you’ll see fences written as ```{python} with braces — that is Quarto and R Markdown’s own extension, marking a block as code to execute instead of merely display. Plain Markdown has no such concept.

The point of the syntax is that the raw file still reads as text. Asterisks around a word make it italic and also look like emphasis; a row of hashes marks a heading and also looks like one.

8.1.2 R Markdown

R Markdown combines R code, output, and narrative text in a single document that can be rendered to HTML, PDF, Word, and other formats.

The idea behind it — “literate programming”, writing the explanation and the code as one document — was proposed by Donald Knuth in 1984 (Knuth 1984).

8.1.2.1 Installing and Using R Markdown

If you’ve installed R and RStudio as described earlier, R Markdown is just a package installation away:

install.packages("rmarkdown")

To create your first R Markdown document:

  1. In RStudio, go to File → New File → R Markdown
  2. Fill in the title and author information
  3. Choose an output format (HTML, PDF, or Word)
  4. Click “OK”

RStudio creates a template document with examples of text, code chunks, and plots, so you don’t start from scratch.

A typical R Markdown document consists of three components:

  1. YAML Header: The block fenced by --- at the top, holding metadata like title, author, and output format. YAML is a plain-text format of key: value settings, with indentation indicating nesting; you’ll meet it again in Docker Compose files and GitHub Actions workflows
  2. Text: Written in Markdown for narratives, explanations, and interpretations
  3. Code Chunks: R code that can be executed to perform analysis and create outputs

For example:

---
title: "My First Data Analysis"
author: "Your Name"
date: "2026-04-30"
output: html_document
---

# Introduction

This analysis explores the relationship between variables X (carat) and Y (price).

## Data Import and Cleaning

```{r data-import}
# load the diamonds dataset from ggplot2
data(diamonds, package = "ggplot2")

# Create a smaller sample of the diamonds dataset
set.seed(123)  # For reproducibility
my_data <- diamonds |>
  dplyr::slice_sample(n = 1000) |>
  dplyr::select(
    X = carat,
    Y = price,
    cut = cut,
    color = color,
    clarity = clarity
  )

# Display the first few rows
head(my_data)
```

## Data Visualisation

```{r visualisation}
ggplot2::ggplot(my_data, ggplot2::aes(x = X, y = Y)) +
  ggplot2::geom_point() +
  ggplot2::geom_smooth(method = "lm") +
  ggplot2::labs(title = "Relationship between X and Y")
```
Note

The example calls functions as package::function() instead of attaching packages with library(). That’s a matter of preference. It keeps same-named functions apart, such as dplyr::filter() and stats::filter(), and it shows beside each call which package the document depends on. :: still loads the package; it only skips attaching it to the search path.

The pipe is |>, which has been part of base R since version 4.1. The older %>% comes from magrittr, so it needs library(dplyr) or library(magrittr) first.

When you click the “Knit” button in RStudio, the R code in the chunks is executed, and the results (including plots and tables) are embedded in the output document. Code, results, and narrative live in one file, so there is no step where a number is copied from a console into a paragraph and then goes stale. If your data changes, re-knit the document and every figure and table updates.

That link between data, analysis and conclusion is what makes the document checkable. Someone who doubts a figure can read the chunk that produced it instead of asking you.

8.1.3 Jupyter Notebooks for Documentation

Notebooks do the same job as R Markdown from the Python side: code, output and prose in one file. The difference is that a notebook stores its output alongside the code, so it can be read without being re-run — convenient for sharing, and the reason two notebooks that look identical can disagree.

8.1.3.1 Exporting Jupyter Notebooks

Jupyter notebooks can be exported to various formats:

  1. In JupyterLab or Notebook 7, go to File → Save and Export Notebook As
  2. Choose from options like HTML, PDF, Markdown, etc.

Alternatively, you can use nbconvert from the command line:

jupyter nbconvert --to html my_notebook.ipynb

One notebook, several outputs: PDF for a formal report, HTML for a website, Markdown for a repository. That saves you maintaining three versions of the same analysis.

8.1.3.2 Jupyter Book

For larger documentation projects, Jupyter Book builds on the notebook format to create complete books:

# Install Jupyter Book (with conda: conda install jupyter-book)
uv pip install jupyter-book

# In the folder holding your notebooks and Markdown files: write the
# configuration file, then start a live-reloading preview
jupyter book init
jupyter book start

Jupyter Book organises multiple notebooks and markdown files into a book with navigation, search, and cross-references — useful for multi-page documentation, tutorials, or course materials.

WarningVersion 2 changed the commands

Installing jupyter-book now gives you version 2, built on the MyST document engine, and its command is jupyter book, two words. Version 1 used hyphenated commands: jupyter-book create my-book, then jupyter-book build my-book/. Older tutorials still show that form, and version 2 rejects it with Invalid command: create my-book.

8.1.4 Quarto

Quarto is a newer system that works with both Python and R, combining R Markdown’s approach with Jupyter notebooks.

# Install Quarto CLI from https://quarto.org/docs/get-started/

# Create a new Quarto project (website, book, manuscript, etc.)
quarto create project default my-project

# Or, for a standalone document, create a file
# named document.qmd in your editor (no command needed).

# Render a document to HTML (or PDF, docx, etc.)
quarto render document.qmd

Quarto is R Markdown’s successor and works the same way for R, but it doesn’t assume R. Python, Julia and Observable chunks all execute, and a single document can mix them. If you work in both Python and R, it means one document format rather than two.

8.1.4.1 Quarto Dashboards

Since Quarto 1.4 (released in 2024), Quarto can render a document directly into a dashboard layout with rows, columns, value boxes, and tab sets, with no Shiny, Dash, or Streamlit required for the static case. If all you need is a periodic refresh of a dashboard view over your data, this is the lightest way to get there: you write a normal .qmd file with a format: dashboard YAML key, and Quarto handles the layout.

---
title: "Sales Overview"
format: dashboard
---
#| title: "Revenue by Quarter"
ggplot(sales, aes(quarter, revenue)) + geom_col()

For interactive behaviour (filters, user inputs), Quarto dashboards can embed Shiny, Observable JS, or even Python/R running in the browser via webR/Pyodide. For readers whose dashboards are read-only and updated nightly, this alone replaces a lot of what used to require a Shiny or Dash server.

8.1.4.2 Parameterised Reports

One of the highest-value Quarto (and R Markdown) features for a business analytics audience is parameterised reports: a single template that you can render with different inputs to produce many tailored outputs. For example, a monthly sales report that takes a region and month parameter and can be rendered once for every region without copy-pasting the document.

---
title: "Sales Report"
format: html
params:
  region: "South Africa"
  month: "2026-03"
---

How you read those values inside the document depends on the engine.

With the knitr engine (R), the YAML block above is all you need — the values arrive in a params list:

cat("Report for", params$region, "covering", params$month)

With the Jupyter engine (Python), Quarto follows papermill’s convention instead: you tag one code cell parameters, assign defaults there as ordinary variables, and refer to them as ordinary variables everywhere else. There is no params object.

#| tags: [parameters]
region = "South Africa"
month = "2026-03"
print(f"Report for {region} covering {month}")

Either way, you render with -P:

quarto render sales.qmd -P region:"EU" -P month:"2026-03"

For the Jupyter engine, -P hands the values to papermill, so install it in the environment first (uv pip install papermill, or conda install papermill). Without it the render stops with The papermill package is required for processing --execute-params. Quarto keeps its Python process running between renders, so if you install papermill after seeing that error, add --execute-daemon-restart to the next render.

This pattern replaces the habit of keeping one copy of a notebook per client.

8.1.5 LaTeX for Professional Document Creation

When a report needs to look like a journal article or a formal business document, LaTeX is the typesetting system that gets it there. Markdown handles simple documents well; LaTeX gives you precise page layout, mathematical notation, figures and tables that number and cross-reference themselves, and bibliographies through BibTeX — all from plain text, so it versions in Git like any other source file.

LaTeX works differently from word processors: you write plain text with special commands, then compile it to a PDF. You don’t need to learn those commands to get the benefit. Quarto and R Markdown generate them from your document and run the compiler for you, so what follows is how to install that compiler and configure Quarto to drive it, rather than a course in LaTeX itself. If you do end up writing raw LaTeX, Quarto’s PDF documentation and the TeX Stack Exchange are where to go.

8.1.5.1 Installing LaTeX for Quarto and R Markdown

The easiest way to install LaTeX for use with Quarto or R Markdown is to use TinyTeX, a lightweight LaTeX distribution:

In R:

install.packages("tinytex")
tinytex::install_tinytex()

In the command line with Quarto:

quarto install tinytex

TinyTeX is built for R Markdown and Quarto users. It installs a minimal set of LaTeX packages rather than the several gigabytes a full distribution takes, and pulls down anything else it needs the first time a document calls for it.

8.1.5.2 Using LaTeX with Quarto

LaTeX options for a PDF go in the document’s YAML header, so the source itself stays readable.

8.1.5.2.1 YAML Configuration

In your Quarto YAML header, specify PDF output with LaTeX options:

---
title: "Analysis Report"
author: "Your Name"
format:
  pdf:
    documentclass: article
    geometry:
      - margin=1in
    fontfamily: libertinus
    colorlinks: true
    number-sections: true
    fig-width: 7
    fig-height: 5
    cite-method: biblatex
    biblio-style: apa
---
8.1.5.2.2 Customising PDF Output

You can further customise the LaTeX template by:

  1. Including raw LaTeX: Use the raw attribute to include LaTeX commands

    ```{=latex}
    \begin{center}
    \large\textbf{Confidential Report}
    \end{center}
    ```
  2. Adding LaTeX packages: Include additional packages in the YAML

    format:
      pdf:
        include-in-header:
          text: |
            \usepackage{siunitx}
            \usepackage{algorithm2e}
  3. Using a custom template: Create your own template for full control

    format:
      pdf:
        template: custom-template.tex
8.1.5.2.3 Equations in Quarto

Quarto supports LaTeX math syntax directly:

The linear regression model can be represented as:

$$
y_i = \beta_0 + \beta_1 x_i + \epsilon_i
$$

where $\epsilon_i \sim N(0, \sigma^2)$.
8.1.5.2.4 Citations and Bibliography

For managing citations, create a BibTeX file (e.g., references.bib):

@article{knuth84,
  author = {Knuth, Donald E.},
  title = {Literate Programming},
  year = {1984},
  journal = {Comput. J.},
  volume = {27},
  number = {2},
  pages = {97--111}
}

Then cite in your Quarto document:

Literate programming [@knuth84] combines documentation and code.

And configure in YAML:

bibliography: references.bib
csl: ieee.csl  # Citation style

The .csl file sets how citations and the reference list are formatted. Download it into your project folder from the Zotero Style Repository; IEEE’s is at https://www.zotero.org/styles/ieee. Leave the csl: line out and Quarto uses its default author-date style.

8.1.6 Troubleshooting LaTeX Issues

LaTeX’s error messages can be cryptic. These are the ones you’re most likely to meet.

8.1.6.1 Missing Packages

If you get an error about a missing package when rendering:

! LaTeX Error: File 'tikz.sty' not found.

TinyTeX normally resolves this for you: when it hits a missing .sty file it looks up which TeX Live package provides it, installs it, and recompiles. That happens by default, so most of the time the error above is one you never see.

When it doesn’t resolve automatically, point TinyTeX at the compilation log and let it work out what’s missing:

tinytex::parse_install("document.log")

Installing by hand is a last resort, and the trap is that the TeX Live package name rarely matches the file name — tikz.sty ships in a package called pgf, not tikz:

tinytex::tlmgr_install("pgf")

8.1.6.2 Figure Placement

If figures aren’t appearing where expected:

\begin{figure}[!htbp]  % The ! makes LaTeX try harder to respect placement

8.1.6.3 Large Tables Spanning Multiple Pages

For large tables that need to span pages:

\begin{longtable}{lrrr}
\caption{Model Results}\\
\toprule
Model & Accuracy & Precision & Recall \\
\midrule
\endhead
% Table contents...
\bottomrule
\end{longtable}

8.1.6.4 PDF Compilation Hangs

If compilation seems to hang, it is usually waiting for input at LaTeX’s interactive error prompt. TinyTeX passes -halt-on-error by default so this is rare, but if you are calling LaTeX yourself, or a package has re-enabled the prompt, force it to fail rather than wait:

# In R
tinytex::latexmk('document.tex', engine_args = '-interaction=nonstopmode')

Then read document.log — the first ! line in that file is the real error.

8.1.7 LaTeX or Typst?

LaTeX has been the standard for scientific documentation for decades. Quarto and R Markdown default to it when you ask for a PDF, which is why it is worth knowing even if you never write a .tex file by hand — and why the errors above are errors you will eventually meet.

It also carries a real learning curve, and for most of what this book’s readers produce, there is now a second option.

8.1.7.1 Typst

Typst is a newer typesetting system aimed at the same output with less ceremony. Its markup is closer to Markdown than to LaTeX:

// Typst syntax
= Introduction
== Subsection

$x = (a + b) / c$  // Math notation

#figure(
  image("plot.png"),
  caption: "Sample Plot"
)

Compare this to equivalent LaTeX:

% LaTeX syntax
\section{Introduction}
\subsection{Subsection}

$x = \frac{a + b}{c}$

\begin{figure}
  \includegraphics{plot.png}
  \caption{Sample Plot}
\end{figure}

It also compiles in a fraction of the time, which you notice when you’re rendering a document every few minutes, and its error messages name the line and say what’s wrong rather than leaving you to read a log.

8.1.7.2 Choosing Your Path Forward

Use LaTeX when something outside your control expects it: a journal template, a supervisor’s preamble, a package that exists nowhere else. Use Typst when nothing does. That covers most business and internal reporting, where nobody cares what produced the PDF.

You don’t have to choose up front. Quarto has shipped the Typst compiler since version 1.4, so switching engines is a one-line YAML change. Ordinary Markdown, code and figures carry over unchanged. Raw LaTeX blocks are left out of Typst output, and LaTeX code in options such as include-in-header has to be rewritten in Typst:

---
title: "Sales Report"
format: typst     # instead of: pdf
---

format: typst produces a PDF without LaTeX installed at all. If PDF output is all you need, you can skip the TinyTeX installation and everything that follows from it.

8.1.8 Creating Technical Documentation

For more complex projects, specialised documentation tools may be needed:

8.1.8.1 MkDocs: Simple Documentation with Markdown

MkDocs creates a documentation website from Markdown files:

# Install MkDocs (with conda: conda install mkdocs)
uv pip install mkdocs

# Create a new project
mkdocs new my-documentation

# Serve the documentation locally
cd my-documentation
mkdocs serve

MkDocs is focused on simplicity and readability. It generates a clean, responsive website from your Markdown files, with navigation, search, and themes — enough for project documentation aimed at users or team members, without a heavier system’s configuration burden.

8.1.8.2 Sphinx: Documentation Generated from Code

Sphinx is the documentation tool the Python ecosystem standardised on:

# Install Sphinx (with conda: conda install sphinx)
uv pip install sphinx

# Create a new documentation project
sphinx-quickstart docs

# Build the documentation
cd docs
make html        # in Windows PowerShell: .\make html

Sphinx offers advanced features like automatic API documentation generation, cross-referencing, and multiple output formats. It’s the system behind the official documentation for Python itself and many major libraries like NumPy, pandas, and scikit-learn.

Sphinx became the standard for Python documentation largely because it generates reference documentation from docstrings — the descriptive text you write inside a function or class, which Python keeps attached to the object at runtime. You document each function where it lives, and Sphinx extracts and formats those descriptions into a browsable reference that can’t drift out of step with the code.

8.2 Reproducible Reports — Working with Data

A report that reads a data file has to find it on whichever machine renders it.

8.2.1 Common Issues with File Paths

The error 'my_data.csv' does not exist in current working directory is a common issue when transitioning between different editing environments like VS Code and RStudio. This happens because:

  1. Different IDEs may have different default working directories
  2. Quarto’s rendering process often sets the working directory to the chapter’s location
  3. Absolute file paths won’t work when others try to run your code

8.2.2 Project-Relative Paths with the here Package

The here package provides an elegant solution by creating paths relative to your project root:

library(tidyverse)
library(here)

# Load data using project-relative path
data <- read_csv(here("data", "my_data.csv"))
head(data)

The here() function automatically detects your project root (usually where your .Rproj file is located) and constructs paths relative to that location. This ensures consistent file access regardless of:

  • Which IDE you’re using
  • Where the current chapter file is located
  • The current working directory during rendering

To implement this approach:

  1. Create a data folder in your project root
  2. Store all your datasets in this folder
  3. Use here("data", "filename.csv") to reference them

8.2.3 Alternative: Built-in Datasets

For maximum reproducibility, consider using built-in datasets that come with R packages:

# Load a dataset from a package
data(diamonds, package = "ggplot2")

# Display the first few rows
head(diamonds)

A dataset that ships with a package has no path to get wrong, and anyone with the package has it. That makes built-in data the right choice for examples and tutorials, where which data you use rarely matters.

8.2.4 Creating Sample Data Programmatically

Another reproducible approach is to generate sample data within your code:

library(tibble)

# Create synthetic data
set.seed(0491)  # For reproducibility
synthetic_data <- tibble(
  id = 1:20,
  value_x = rnorm(20),
  value_y = value_x * 2 + rnorm(20, sd = 0.5),
  category = sample(LETTERS[1:4], 20, replace = TRUE)
)

# Display the data
head(synthetic_data)

This approach works well for illustrative examples and ensures anyone can run your code without any external files.

8.2.5 Remote Data with Caching

For data that doesn’t ship with a package, read it from a stable URL. The chunk below reads the copy of diamonds kept in ggplot2’s GitHub repository, so you can compare it with the built-in version above. The cache: true line in its options saves the result, so the download doesn’t repeat on every render:

```{r}
#| label: remote-data
#| cache: true
#| message: false

url <- "https://raw.githubusercontent.com/tidyverse/ggplot2/main/data-raw/diamonds.csv"

# Download and read the data
remote_data <- readr::read_csv(url)

# Display the data
head(remote_data)
```

Quarto re-runs a cached chunk only when its code changes. If the file at the URL changes, delete the document’s _cache folder to fetch it again.

8.2.6 Best Practices for Documentation

Write it as you go. Left to the end, documentation tends not to get written, and by then you’ve forgotten why you made many of the choices you’re trying to describe.

Writing a modelling choice down in prose is also a good test of whether you can justify it.

8.3 Conclusion

This chapter covered the document side of data science output: Markdown and Quarto for literate programming, LaTeX and Typst for publication-quality typesetting, parameterised reports for templating, and data-loading patterns that survive being run on someone else’s machine.

By the end of this chapter you should have:

  • One .qmd document that renders to HTML, containing both prose and a code chunk whose output appears in the result
  • The same document rendered to PDF, with TinyTeX installed — or Typst configured instead, if you’d rather not install a LaTeX distribution at all
  • A report that loads its data by a path that works on someone else’s machine, using here() or an equivalent, rather than an absolute path from yours
  • At least one parameterised render, so you’ve seen the same document produce two different outputs from the same source

What we haven’t covered yet are the charts that live inside these documents and the interactive applications that extend beyond them:

  • The Data Visualisation chapter covers the static and lightly-interactive plotting libraries you’ll embed in reports (matplotlib, seaborn, plotly, ggplot2), plus Mermaid for code-based diagrams.
  • The Web Development for Data Scientists chapter covers the tools for when “rerun the render” isn’t enough and stakeholders need to poke at the data themselves: Shiny, Dash, Streamlit, and Flask.

Pick whichever matches what your reader needs.