× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Finding Your D3 Data

Jonathan Eunice
Dec 12, 2014
<p><a href="http://d3js.org/">D3.js</a> is a great data display system—whether for SVG graphics or more common HTML elements. But you can get “lost in the woods.” Its fluent, functional style can leave you wondering “What data were we working on here?!”</p><p>The more nested the data, and the more transitions and animations are involved, the greater the risk that you “lose context” of what data you’re handling. Making matters worse, JSON is probably the most common data source—and almost all real-world JSON is heavily nested.</p><p>The forest only thickens when you start modularizing your program into separate functions. It’s great practice, but passing around selections and having handler functions called on real-time events (e.g. after <code>.on("click", handle_click)</code> and <code>.on("mouseover", hover_handler)</code> kind of calls), and now you have another layer of indirection and possible confusion.</p><p><code>d3.select(this)</code> is your friend. In handlers, it will select the current element, and let you get back into chaining D3 calls in the current context. If you need an explicit reference to the related data, try: <code>d3.select(this).datum()</code>. If the item selected is an SVG element, and you need to get back to the enclosing HTML element, try <code>d3.select(this.offsetParent)</code> Or if the <code>.offsetParent</code> is a <code>&lt;td&gt;</code> say, and you need to get back to the enclosing row (<code>&lt;tr&gt;</code>), then <code>d3.select(this.offsetParent.parentNode)</code> might well do the trick.</p><p>Note that raw JavaScript DOM reference can then be turned into D3 selections (a similar trick is often used in jQuery).</p><p>Another technique is an oldie but goodie: Print statements. Or since this is JavaScript, <code>console.log()</code> and the browser’s debugging console. Logging calls can be dropped right into any of your D3 calls. Make sure when you do that you use a descriptive label. <code>console.log("after append", d)</code> tells you a lot more than just <code>console.log(d)</code>. It signals where in the woods you are!</p><p>Understanding what the data is—that’s great. Understanding what the data is, and <em>where</em> it has those given values—that’s what context is all about. That’s what gets you out of the woods.</p>
comments powered by Disqus