Overview

Often times a D3 visualization will require additional components such as CSS styles, JavaScript helper functions, or even entire JavaScript libraries. This article describes how to include these dependencies along with your visualization.

CSS Styles

It’s common to require a few CSS styles when creating a visualization. By convention, if you include a CSS file with the same base filename as your D3 script file it will automatically be included. For example, consider a D3 script “barchart.js” within a sub-directory:

If you render the “barchart.js” script like this:

r2d3(data=c(0.3, 0.6, 0.8, 0.95, 0.40, 0.20), script = "barchart.js")

Then the “barchart.css” file will be automatically included.

You can also name a CSS file “styles.css” (useful if you want multiple visualizations to share styles) and it will also be automatically included:

Finally, you can explicitly include a CSS file of any name via the css parameter of r2d3():

r2d3(data=c(0.3, 0.6, 0.8, 0.95, 0.40, 0.20), script = "barchart.js", css = "theme.css")

d3-jetpack

The r2d3 package has built-in support for d3-jetpack, a set of convenience wrappers designed to speed up daily work with d3. You can include d3-jetpack in your visualization by specifing “d3-jetpack” in the dependencies parameter of r2d3(). For example:

One commonly used d3-jetpack function is d3.conventions(). To use d3.conventions() with r2d3 you need to forward the root element and size information provided automatically by r2d3 to d3.conventions() as follows:

JavaScript

If your visualization depends on additional JavaScript files (e.g. a d3 extension or some common code that you want to re-use) you can specify this using the dependencies parameter of r2d3(). For example:

External Libraries

You can include entire external libraries as dependencies by passing an “html_dependency” object created using the htmltools::htmlDependency() function. For example, here’s how you would include the version of jQuery bundled with the rmarkdown package:

Note that you can pass a list of multiple dependencies (either paths to JavaScript files or “html_dependencies” objects) via the dependencies argument.