Unlocking the power of D3.js

A couple of months ago, I attended a workshop on D3.js at the St. Louis Machine Learning & Data Science meetup, which got me really excited to start playing around with it. It's a Javascript library for building interactive data visualizations on the web. I'm only now getting around to exploring this incredible tool and wanted to try to get a visualization to work within my Squarespace blog. I came across a helpful blog post by Toke Frello that explained (mostly) how to do it, which turns out to be rather straightforward.

In the above demo (you can grab the nodes and move them around), I'm using an example taken from the book 'Interactive Data Visualization for the Web' by Scott Murray (Ch. 11, ex 4 to be specific), which I first learned about through the workshop. The key steps to get it to work properly within my blog were:

  1. Upload the d3.js library file, and then add the following to the 'Code Injection' section under advanced 'Blog Settings': <script src="/s/d3.js"></script>. You may also want to inject css styling there as well. This step only has to be done once, obviously.
  2. Create a code block in your blog post. Start the block with a <div> tag that you can reference in the javascript code, e.g. <div class="mydiv"></div>, and then paste in the visualization code, i.e. the entire <script type="text/javascript"> element. 
  3. The key trick was to change the d3.select("body") to d3.select(".mydiv") , which will then place the svg element within the custom div tag.

That's all there is to it.  I'm excited to start creating my own visualizations!