15.5 Visualization with D3

The R package r2d3 (Strayer, Luraschi, and Allaire 2022) is an interface to D3 visualizations. This package can be used in R Markdown documents as well as other applications (e.g., Shiny). To use it in R Markdown, you can either call its function r2d3() in a code chunk, or use its d3 engine. The latter requires you to understand the D3 library and JavaScript, which are beyond the scope of this book, and we will leave it to readers to learn them. Below is an example of using the d3 engine to draw a bar chart:

---
title: Generate a chart with D3
output: html_document
---

First, load the package **r2d3** to set up the `d3` engine
for **knitr** automatically:

```{r setup}
library(r2d3)
```

Now we can generate data in R, pass it to D3, and draw
the chart:

```{d3, data=runif(30), options=list(color='steelblue')}
svg.selectAll('rect')
  .data(data)
  .enter()
    .append('rect')
      .attr('width', function(d) { return d * 672; })
      .attr('height', '10px')
      .attr('y', function(d, i) { return i * 16; })
      .attr('fill', options.color);
```

References

Strayer, Nick, Javier Luraschi, and JJ Allaire. 2022. R2d3: Interface to D3 Visualizations. https://rstudio.github.io/r2d3/.