Charts on this blog: a working example

Not a post: a reference page showing how interactive charts and R/Python figures go into a post. Linked from the README only.

This page is not listed anywhere on the site. It exists so you can copy from it. The chart below is an Observable JS cell: it is written in the post, runs in the reader’s browser, follows light/dark mode, and needs nothing installed. The data file nino34.csv sits next to this page (put a post’s data next to its index.qmd).

The code for this chart

Copy this into a post (as an {ojs} cell) and change the data and the marks. theme(dark) gives you the blog’s fonts, quiet axes and the chart colours; colors(dark) gives you the individual colours (series, sequential, diverging, ink, muted, …).

```{ojs}
import {darkMode, theme, colors} from "/assets/viz.js"
dark = darkMode()
data = FileAttachment("my-data.csv").csv({typed: true})
Plot.plot({
  ...theme(dark),
  marks: [
    Plot.lineY(data, {x: "year", y: "value", stroke: colors(dark).series[0], strokeWidth: 2}),
    Plot.tip(data, Plot.pointerX({x: "year", y: "value"}))
  ]
})
```

Figures from R or Python

Code in {r} or {python} cells runs once when you render the post, and the figure is saved (_freeze/), so the site never needs R or Python to be rebuilt. With renderings: [light, dark] the cell makes two versions and the reader sees the one matching their mode.

```{r}
#| renderings: [light, dark]
#| fig-alt: "Monthly Niño 3.4 anomalies since 1950"
library(ggplot2)
source("../../assets/theme_divergences.R")
p <- ggplot(enso, aes(month, anomaly)) + geom_line(linewidth = 0.6)
p + theme_divergences("light")
p + theme_divergences("dark")
```
```{python}
#| renderings: [light, dark]
import matplotlib.pyplot as plt
for mode in ["light", "dark"]:
    plt.style.use(f"../../assets/divergences-{mode}.mplstyle")
    fig, ax = plt.subplots()
    ax.plot(x, y)
    plt.show()
```

A figure you already have (a PNG or SVG) is just an image: put the file next to the post and write ![Caption that appears under the figure](figure.png){fig-alt="What the figure shows, for screen readers"}.

Back to top