15.5 Visualization with D3

The R package r2d3 (Luraschi and Allaire 2018) 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:

  1. ---
  2. title: Generate a chart with D3
  3. output: html_document
  4. ---
  5. First, load the package **r2d3** to set up the `d3` engine
  6. for **knitr** automatically:
  7. ```{r setup}
  8. library(r2d3)
  9. ```
  10. Now we can generate data in R, pass it to D3, and draw
  11. the chart:
  12. ```{d3, data=runif(30), options=list(color='steelblue')}
  13. svg.selectAll('rect')
  14. .data(data)
  15. .enter()
  16. .append('rect')
  17. .attr('width', function(d) { return d * 672; })
  18. .attr('height', '10px')
  19. .attr('y', function(d, i) { return i * 16; })
  20. .attr('fill', options.color);
  21. ```

References

Luraschi, Javier, and JJ Allaire. 2018. R2d3: Interface to D3 Visualizations. https://github.com/rstudio/r2d3.