11 Share D3 online

There are a number of ways you can share your D3 code online. Even if you’re not sharing, there are advantages to an online setup, for example, not having to set up a local server as described in the chapter on reading files.

11.1 Quarto

Separate .js file

Video tutorial

To include D3 in a Quarto document, I recommend putting the script in a separate .js file that is linked to both by a .qmd file in your project as well as a temporary .html file that you’ll use while creating the visualization. The rationale is that you won’t have to Quarto render your book / web site each time you update the D3 script.

  1. Create a .qmd file for the visualization

Create a .qmd file with a link to the D3 library, a link to your D3 script, a <div> for adding an svg in the right place and any additional HTML needed for your visualization.

Use can use this file as a template.

Note that you do not need <head>, <title>, or <body> tags as these are added in the process of converting the .qmd files to HTML.

Example: d3graph.qmd

  1. Create a .js file for your D3 script

This file should contain your script. To ensure that the svg will appear in the book (and not below it) append the svg to the <div> in your .qmd file.

Example: myscript.js

  1. Create a separate .html for development purposes

Create an .html file with the same contents as your .qmd file. With this setup you can test your code without rendering the book but simply opening the .html file.

Example: practice.html

iframe

Create your entire visualization in a separate .html file and then include in your .qmd file with <iframe>:

<iframe src="mybarchart.html" width="400" height="300"></iframe>

You can work on the .html file separately and view updates without rendering the book.

11.2 Observable

Observable, created by D3 author Mike Bostock, is the official D3 web tool for creating and sharing D3 code. It is a powerful, popular tool–all new D3 code examples are now presented in Observable–but program flow is different than it is for stand-alone JavaScript. If you’re interested in learning more, see Why Observable.