How do I work with the D3 Sankey Example?

Hi!

Code in Observable notebooks is indeed written in JavaScript, but in general, you can’t just copy and paste the code into an ordinary script. Notebooks are executed using the Observable “runtime”. See the tutorials “How Observable Runs” and “Downloading and Embedding Notebooks” for some more info. As explained on the latter page, the easiest and most general way to get a copy of a notebook running on another page is to click the menu in the top right and choose the “Download tarball” link, and then put those files on a webserver.

See also this similar question on the forums a few weeks ago.

As with the notebook in the other thread, I thought it might be interesting / educational for me to try to get the notebook code working outside the Observable runtime environment in your fiddle so I took a crack at it. Here’s the updated fiddle; sorry about the lack of indentation:

https://jsfiddle.net/s3opcnm8/

Here are some brief notes on how I did the conversion:

  • In the HTML file, I fixed the script tags and then put in a container SVG element
  • In the JS file, I moved all of the code out of “cell blocks” (i.e. the stuff like the code you quoted in your first post) since that’s Observable notebook syntax:
    • the return statements became variable assignments to e.g. color and sankey
    • this required renaming some of the variables that were previously cell-scoped, see e.g. _color and _sankey and sankey,
  • Next, I reordered the JS code so that nothing was referencing anything before it was defined
  • Since that the chart depends on an external data file which has to be loaded, I wrapped most of the D3 code in a “.then” call to d3-json (since that function returns a Promise)
  • I then adapted the code depending on DOM.uid since that depends on the Observable standard library.
  • The final step was to deal with the fact that the “path” objects defined by the “link” selection in the SVG depend on the variable “edgeColor”, which comes from a “select” input.
    • I copied the HTML for the select input from the notebook into the HTML file of the fiddle
    • I wrapped the code that depended on “edgeColor” in an update function
    • I wrote an “onchange” handler for the select input to update “edgeColor” and call update

As you can see, it’s a lot of steps, so I will reiterate my recommendation that for “copying” general notebooks you use the technique described in the Downloading and Embedding tutorial.

3 Likes