<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by lars verspohl on Medium]]></title>
        <description><![CDATA[Stories by lars verspohl on Medium]]></description>
        <link>https://medium.com/@lverspohl?source=rss-3ed15968ada5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*obkJg_b6lHGrm9pnzD8RjQ.png</url>
            <title>Stories by lars verspohl on Medium</title>
            <link>https://medium.com/@lverspohl?source=rss-3ed15968ada5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 05:40:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lverspohl/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Want an introduction to D3 Zoom? Check out this primer.]]></title>
            <link>https://medium.com/@lverspohl/want-an-introduction-to-d3-zoom-check-out-this-primer-9c07fa0be4ba?source=rss-3ed15968ada5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c07fa0be4ba</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[lars verspohl]]></dc:creator>
            <pubDate>Tue, 16 Jan 2018 16:10:25 GMT</pubDate>
            <atom:updated>2018-01-16T18:46:04.787Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wd4f16imQvUAVjeDb_3HRQ.png" /><figcaption>‘<a href="https://fineartamerica.com/featured/1895-firemans-ladder-patent-blueprint-aged-pixel.html">1895 Firemans Ladder Patent — Blueprint</a>’ by <a href="https://www.agedpixel.com/">Aged Pixel</a></figcaption></figure><p>This is a summary of my longer, much more in-depth tutorial published <a href="https://medium.freecodecamp.org/get-ready-to-zoom-and-pan-like-a-pro-after-reading-this-in-depth-tutorial-5d963b0a153e">here</a> and on my <a href="http://www.datamake.io/blog/d3-zoom">blog</a>. In this article, I’ll introduce you to 5 simple synchronous steps to get started with D3 zooming and panning.</p><h3>Some terminology first</h3><ul><li>A <strong>zoom transform</strong> is a simple object produced and maintained by D3. It holds three values: the <em>x</em> and <em>y</em> translation as well as the scale factor called <em>k</em>. This is how it looks in its initial state:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/0*a2gCiM6ymzdRFrNK.jpg" /></figure><ul><li>The <strong>zoom behaviour</strong> is the event system that keeps track of and passes on the transform values. A listener consumes the user’s actions. Once activated, it will send an event object with information about this event to a handler function you write. The most important piece of information your handler will receive is the above transform at every zoom activity. In its simplest from, you set the zoom behavior up like so:</li></ul><pre>var zoom = d3.zoom().on(‘zoom’, zoomed);</pre><ul><li>The <strong>zoom base</strong> is the parent element the zoom is attached to or registered on, as they say. It’s the surface that takes in all the user’s moves and gestures, and it holds the transform object (the <em>x</em>, the <em>y,</em> and the scale factor <em>k</em>).</li><li>The <strong>zoom targets</strong> are all the elements we want to move around. If you want to zoom in and out of a circle, then this circle would be your zoom target.</li></ul><p>We also distinguish between two types of zoom:</p><ul><li><strong>Geometric zoom</strong> means elements just get scaled up or down without any differentiation. All their properties will get scaled up or down. Think of it as moving or scaling the coordinate system of the respective elements.</li><li><strong>Semantic zoom</strong> means we control each single element’s property during the zoom. You are taking control over every aspect of your element’s moves.</li></ul><h3>The manual</h3><h4><strong>1. Build your static visual first</strong></h4><p>In order to zoom into a visual, you will need a visual.</p><h4><strong>2. Identify your zoom base and your zoom targets</strong></h4><ul><li>Choose your zoom base element first. You can attach the zoom to an svg, g, rect or any other element that your mouse has access to. Note here that g elements can only register events where they have children with a fill. So, if you have a large g element with a circle of radius 1, your zoom gestures will only work on that tiny circle. It’s often best to set-up a dedicated SVG rectangle (rect) with fill but 0 opacity and pointer-events set to all to register the zoom listener on. You might have to unset pointer events of ascendant elements.</li><li>Identify your target elements and write them down. Which elements do you want to move? Make a list of all elements that will move.</li><li>For each target, identify if you want to use geometric or semantic zoom. You should note down which properties for each target you want to change.</li><li>Here’s an example table you might end up with:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2yg58wl4GfCJly_T1C-bFw.png" /></figure><p><strong>3. Set up the zoom behaviour</strong></p><ul><li>Create the zoom behaviour with at least:</li></ul><pre>var zoom = d3.zoom().on(‘zoom’, zoomed);</pre><ul><li>Check out the <a href="https://github.com/d3/d3-zoom">D3 API reference for d3.zoom()</a> for helper methods like scaleExtent and translateExtent.</li><li>Call the zoom behaviour on your base element like this:</li></ul><pre>zoomBaseElement.call(zoom)</pre><p><em>You don’t have to call your zoom base </em>zoomBaseElement <em>of course.</em></p><h4><strong>4. Write the handler</strong></h4><ul><li>The first thing you want to do is capture the transform object passed into the handler by the listener at every user interaction (wheel or mouse):</li></ul><pre>var transform = d3.event.transform;</pre><ul><li>Now that you have all 3 values, you need to do whatever you want with it: <em>tx</em>, <em>ty</em> and the scale <em>k</em>.</li><li>If you want to only administer <strong>geometric zoom</strong>, you just call</li></ul><pre>zoomTargetElement<br>  .attr(‘transform’, <br>        ‘translate(‘ + transform.x + ‘, ‘ + transform.y + ‘) <br>         scale(‘ + transform.k + ‘)’);</pre><p>or simpler:</p><pre>zoomTargetElement.attr(‘transform’, transform.toString());</pre><p>which is exactly the same. This assumes you want to apply all transform values. You can also focus on <em>tx</em>, <em>ty</em> or only the scale <em>k</em>,<em> </em>of course.</p><ul><li>If you want<strong> semantic zoom</strong> you need to rescale.</li><li>Assuming all your data values went through a scale to be translated from data to screen space, this translation changes on zoom. If your data point x = 10 was translated to pixel space 50 before zoom, the zoom will move it to a different point.</li><li>Assuming you translate the x by 5 and scale by 2, the new position will be</li></ul><blockquote>x2 = x1 × k + tx <em>or</em><br>x2 = 50 × 2 + 5 = 105.</blockquote><ul><li>Luckily you don’t have to produce these calculations yourself (you could now). You can rescale your scale on each zoom and apply it to the target properties you want to change. This includes axes or circles or rects or whatever target shapes and components you have.</li><li>Assuming you have a scale called xScale, you can use the sugar function .rescaleX() and apply it like so:</li></ul><pre>var updatedScale = transform.rescaleX(xScale);</pre><ul><li>Now you can use updatedScale in your zoomed function for all the elements you want to update. For example an axis:</li></ul><pre>xAxis.scale(updatedScale); gAxis.call(xAxis);</pre><ul><li>Or a set of circle x positions:</li></ul><pre>circles.attr(‘cx’. function(d) { return updatedScale(d.value); })</pre><h4><strong>5. Do you need to programmatically move your target into a position?</strong></h4><ul><li>Calculate/determine the position and the scale</li><li>Capture the new positions tx and ty and the new scale k in D3’s own transform object format by saying</li></ul><pre>var t = d3.zoomIdentity.translateBy(tx, ty).scale(k);</pre><ul><li>Store the object in the zoom base AND propagate the changes by calling your first zoom handler, which will move the targets with</li></ul><pre>zoomBaseElement.call(zoom.transform, t);</pre><ul><li>Now enable user triggered zoom with</li></ul><pre>zoomBaseElement.call(zoom)</pre><p>That was it! You can read the full article with pictures in pink and blue and sources and all that over <a href="https://medium.freecodecamp.org/get-ready-to-zoom-and-pan-like-a-pro-after-reading-this-in-depth-tutorial-5d963b0a153e">here</a> or on my blog at <a href="http://www.datamake.io/blog/d3-zoom">Understanding D3 Zoom in SVG and Canvas</a>. Thanks!</p><p><em>Read more of my work on my blog at </em><a href="http://www.datamake.io/blog/d3-zoom-manual"><em>datamake.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c07fa0be4ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[D3 zoom — the missing manual]]></title>
            <link>https://medium.com/free-code-camp/get-ready-to-zoom-and-pan-like-a-pro-after-reading-this-in-depth-tutorial-5d963b0a153e?source=rss-3ed15968ada5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d963b0a153e</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[lars verspohl]]></dc:creator>
            <pubDate>Tue, 16 Jan 2018 16:06:13 GMT</pubDate>
            <atom:updated>2019-04-28T22:09:04.191Z</atom:updated>
            <content:encoded><![CDATA[<h3>D3 Zoom: The Missing Manual</h3><h4>How to zoom and pan in your data visualizations using SVG and Canvas</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xQbd3tLH8julKZ9G7MCuQQ.png" /><figcaption>‘<a href="https://fineartamerica.com/featured/telescope-zoom-lens-patent-from-1999-blueprint-aged-pixel.html">Telescope Zoom Lens Patent From 1999 — Blueprint</a>’ by <a href="https://www.agedpixel.com/">Aged Pixel</a></figcaption></figure><p>The best opening paragraph for a D3 zoom article has already been written, and it goes like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZkhebliOG8iX_OF3.jpg" /><figcaption>Peter Kerpedijec on Empty Pipes (see <a href="#28f2">sources</a> below)</figcaption></figure><p>It’s good. In four sentences, it tells you precisely what zooming is and what it does, and — probably more importantly — it takes away your zooming fears.</p><p>So, has it all been said then? Well, it never has. It’s always good to have numerous differing perspectives, especially with events that move your precious visual all over the shop and scale it around at your trigger-happy user’s discretion.</p><p>A while ago, I worked on a fairly complex visualization with many moving elements and a long list of interactions, including zoom and pan, at its initially dark heart. The static visual itself was already relatively complex, but adding zoom and pan to it felt a bit like tying my son’s 4 by 6 foot Lego castle onto a fleeing water buffalo.</p><p>The conceptual problem here is that zoom and pan so fundamentally interfere with our work. They appear to control quite a bit of our handcrafted visualization, which is rarely ever a single whole thing, but a careful concoction of positions, scales and axes. This can be confusing at best and intimidating at worst.</p><p>So, after my zoom and pan moves grew in confidence, and were tested in a few other projects, the time seemed ripe to write them down. Maybe it’s too late and you all cracked it years ago, but even then, it might be helpful to have another perspective.</p><p>There will be three parts to our journey:</p><ol><li>A synchronous recipe for zoom and pan</li><li>Building a visual</li><li>Implementing zoom and pan in SVG and in Canvas</li></ol><p>As a bonus, we’ll add programmatic zoom and make our visual pretty.</p><p>Now, you might look to that scroll bar over there, thinking you’ll miss supper when reading all this. It’s detailed for a reason, but I’ll make it easy for you to browse and cherry pick as I point out sections you can jump over without missing crucial stuff. So you can make this ride as short or thorough as you like and get something out of it either way.</p><h3>A simple zoom and pan recipe</h3><p>This first part is this post’s spine. It’s a short manual — nothing more than a series of five simple points you can follow while building up your zoom and pan events. This manual will give you a lifeline-like sequence of how to integrate zoom and pan into your app. The asynchronous and knotted world of programming is often helped by a series of synchronous and simple steps to follow.</p><h4>Agreeing on some terminology</h4><p>Before we pull ourselves along the line, let’s first define some helpful terminology:</p><ul><li>A <strong>zoom transform</strong> is an object produced and maintained by D3. It’s your most valuable possession in the zoom and pan context, and it holds three values: the <em>x</em> and <em>y</em> translation as well as the scale factor represented by <em>k</em>. We shall see when and where it gets produced and changed very soon. This is how it looks in its initial state:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/0*i7AY_6MGMfj8Cn-Q.jpg" /></figure><ul><li>It says: <em>“The user has not yet zoomed, or panned the visual. Therefore, the zoom-scale factor is 1 and x and y translation is 0.”</em></li><li>The <strong>zoom behaviour</strong> is the event system that keeps track of and passes on the transform values. A listener consumes (takes note of) the user’s actions. Once activated, it will send an event object with information about this event to a handler function. You will write this handler and use the information of the event object. The most important piece of information your zoom handler will receive is the above transform at every zoom activity. Whatever we want to do with the transform values, we will do in the zoom handler. This might sound like a lot, but in its simplest form you set the zoom behaviour up like so:</li></ul><pre>var zoom = d3.zoom().on(‘zoom’, zoomed);</pre><ul><li>The <strong>zoom base</strong> is the parent element the zoom is attached to or <em>registered on</em>, as they say. It does two things: 1) It’s the surface that takes in all the user’s moves and gestures, and 2) it holds the transform object (the <em>x</em>, the <em>y,</em> and the scale factor <em>k</em>).</li><li>The <strong>zoom targets</strong> are all the elements we want to move around. If you want to zoom in and out of a circle, then this circle would be your zoom target.</li></ul><p>Furthermore, we might want to distinguish between two types of zoom. They will become much clearer when we move to our examples, but it will be helpful to define them on a top-level first:</p><ul><li><strong>Geometric zoom</strong> (or <em>graphical zoom</em>) means elements just get scaled up or down without any differentiation. All their properties will get scaled up or down. Think of it as moving or scaling the coordinate system of the respective elements. Everything on it will be scaled and moved indiscriminately. Geometric zoom is closest to our real-life experience. When we walk towards a house, each aspect of the house appears larger at each step. Equally, if we scale an axis all parts of it would become larger or smaller — the lines, the domain path, the labels. For example, a 14px axis label scaled up by a scale factor of 2 would appear <em>14 × 2 = 28px</em> large.</li><li><strong>Semantic zoom</strong> (or <em>non-geometric zoom</em>) means we control each single element’s property during zoom. If we have an axis, for example, with labels of size 14px and we semantically zoom in to the axis, we could command the labels to retain their original size for every scale factor. The lines might become larger and thinner and the axis would be repositioned according to the zoom, but our label would remain 14px large.</li></ul><p>We won’t touch on this in the following, but bona fide semantic zoom can go further. It allows us to not only control the element’s properties, but the representation of our element depending on the zoom level. Google maps for example shows countries when zoomed out, states or administrational districts at medium zoom and smaller cities when zoomed in.</p><h4>Zoom and pan in 5 steps</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wd4f16imQvUAVjeDb_3HRQ.png" /><figcaption>‘<a href="https://fineartamerica.com/featured/1895-firemans-ladder-patent-blueprint-aged-pixel.html">1895 Firemans Ladder Patent — Blueprint</a>’ by <a href="https://www.agedpixel.com/">Aged Pixel</a></figcaption></figure><p>We are well-equipped for this now. Here’s our zoom and pan in five simple steps:</p><h4>1. Build your static visual first</h4><p>In order to zoom into a visual, you will need a visual.</p><h4>2. Identify your zoom base and your zoom targets</h4><p>Take a piece of paper, nominate an element that listens (the <em>zoom base</em>), and write down a list of elements that should move (the <em>zoom targets</em>).</p><ul><li>Choose your <strong>zoom base</strong> element first. Determine which DOM element you want to use for your zoom base. You can attach the zoom to an svg, g, rect or any other element that your mouse has access to. Note here, that g elements can only register events where they have children with a fill. So, if you have a large g element with a circle of radius 1, your zoom gestures will only work on that tiny circle. It is often best to set-up a dedicated SVG rectangle (rect) with fill but 0 opacity and pointer-events set to all to register the zoom listener on. You might have to unset pointer events of ascendant elements.</li><li>Identify your <strong>zoom target</strong> elements and write them down. Remember, the zoom targets are the elements you want to move. Make a list of all zoom target elements.</li><li>For each target, identify if you want to use <strong>geometric</strong> or <strong>semantic zoom</strong>.</li><li>Note it down. Here’s an example table you might end up with:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2yg58wl4GfCJly_T1C-bFw.png" /></figure><h4>3. Set up the zoom behaviour</h4><p>Now you want to set up the behaviour that will make the listener listen.</p><ul><li>Create the zoom behaviour with at least:</li></ul><pre>var zoom = d3.zoom().on(‘zoom’, zoomed);</pre><ul><li>Check out the <a href="https://github.com/d3/d3-zoom">D3 API reference for d3.zoom()</a> for helper methods like scaleExtent and translateExtent.</li><li>Call the zoom behaviour on your base element like:</li></ul><pre>zoomBaseElement.call(zoom)</pre><p><em>Note, you don’t have to call your zoom base </em>zoomBaseElement<em> of course.</em></p><h4>4. Write the handler</h4><p>This is where the zoom and pan will happen. The handler’s single most precious possession will be the transform object updating <em>x</em>, <em>y,</em> and <em>k</em> continuously when the user wheels or drags. You will apply these to your zoom targets.</p><ul><li>The first thing you want to do is capture the transform object passed into the handler by the listener at every user interaction (wheel or mouse):</li></ul><pre>var transform = d3.event.transform;</pre><ul><li>Now that you have your zoom and pan parameters (<em>tx</em>, <em>ty</em>, <em>k</em>), you can do whatever you want with it...</li><li>If you only want to administer <strong>geometric zoom</strong>, you just call:</li></ul><pre>zoomTargetElement<br>  .attr(‘transform’, <br>        ‘translate(‘ + transform.x + ‘, ‘ + transform.y + ‘) <br>         scale(‘ + transform.k + ‘)’);</pre><p>or simpler:</p><pre>zoomTargetElement.attr(‘transform’, transform.toString());</pre><p>…which is exactly the same. This assumes you want to apply all transform values. You can also focus on only <em>tx</em>, <em>ty</em> or the scale <em>k </em>of course.</p><ul><li>If you want<strong> semantic zoom</strong> you need to rescale.</li><li>Assuming all your data values went through a scale to be translated from data to screen space, this translation changes on zoom. If your data point x = 10 was translated to pixel space 50 before zoom, the zoom will move it to a different point.</li><li>If you translate the x by 5 and scale by 2, the new position will be:</li></ul><blockquote>x2 = x1 × k + tx <br>x2 = 50 × 2 + 5 = 105</blockquote><ul><li>Luckily, you don’t have to (nor should you) produce these calculations yourself, but you can rescale your scale on each zoom and apply it to the target properties you want to change. These include axes or circles or rects or whatever target shapes and components you have.</li><li>With a scale called xScale, you can use the sugar function .rescaleX() and apply it like so:</li></ul><pre>var updatedScale = transform.rescaleX(xScale);</pre><ul><li>Now you can use updatedScale in your zoomed function for all the elements you want to update. For example an axis:</li></ul><pre>xAxis.scale(updatedScale); gAxis.call(xAxis);</pre><ul><li>or a set of circle x positions:</li></ul><pre>circles.attr(‘cx’. function(d) { return updatedScale(d.value); })</pre><h4>5. Do you need to programmatically move your target into a position?</h4><ul><li>Calculate/determine the position and the scale</li><li>Determine the new positions <em>tx</em> and <em>ty</em> and the new scale <em>k</em> in D3’s own transform producing function by saying:</li></ul><pre>var t = d3.zoomIdentity.translateBy(tx, ty).scale(k);</pre><ul><li>Store the object in the zoom base AND propagate the changes by calling your first zoom handler, which will move the targets with:</li></ul><pre>zoomBaseElement.call(zoom.transform, t);</pre><ul><li>Now enable user triggered zoom with:</li></ul><pre>zoomBaseElement.call(zoom)</pre><p>Here you are. I think they call this an executive summary. However, we have only superficially touched on the key concepts and haven’t even mentioned different renderers. Let’s add some flesh to the bones with a real life example.</p><h3>What we make</h3><p>Here’s the Guinea pig we shall build in passing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*C3oWWi9qcRmMAah-.gif" /><figcaption><a href="https://bl.ocks.org/larsvers/raw/c894849af45ce94dc85d76467980f922/">this looks even better on the final site.</a></figcaption></figure><p>It’s a visualisation of our solar system’s planets showing their distance from the Sun. Zooming will come in handy to allow an overview, and panning conveys some feel for distance. In addition, all orbs are pink!</p><p>Oh, and you don’t really have to, but if you want, you can follow along. <a href="https://github.com/larsvers/Understanding-Zoom">Go here for all commented code</a>. Alternatively, you can just play around with the app <a href="https://bl.ocks.org/larsvers/93b2f692217845d51fc75cd43c029303">step by step</a>. I’ll drop a link whenever we progress.</p><h3>Building our static visual</h3><p>As with nearly all visualisations, data is our starting point. So, here it is in its entirety:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*3jPPAMMMwSTN_w445npS5Q.png" /></figure><p>We have 8 planets, 1 star called Sun, and Pluto, which is not actually a planet anymore but still in here for romantic reasons. We also have each planet’s distance from the sun and their radii. That’s all we need. But in order to turn it into this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hOFRsrwGdyTzCVIb.jpg" /></figure><p>…we need to write some code.</p><p>Please note: this post is about zooming rather than about building a static visualization of our solar system. Nevertheless, I will run through the code to give you a round-trip of this app. However, if you’re only here for the zoom, please feel free to browse through this section and quickly move on to the first zoom-building step called <a href="#c311">Identifying our zoom base and zoom targets</a> (mind you, it might be worth reading the <a href="#b9f7">Calculating the Dimensions</a> section in a moment).</p><p>Let’s start with the sparse HTML:</p><pre>&lt;h1 id=&quot;headline&quot;&gt;Measuring our planets&#39; <br>  &lt;span id=&quot;pink&quot;&gt; <br>    &lt;a href=&quot;http://bit.do/solar-system&quot;&gt;distances&lt;/a&gt; <br>  &lt;/span&gt; <br>&lt;/h1&gt; </pre><pre>&lt;div id=&quot;vis&quot;&gt;&lt;/div&gt;</pre><p>That’s it. We have a headline with a link and a span to give it an appropriately pink bottom border and a container div for our vis. Now we’ll move swiftly on to the JavaScript and bypass the CSS, which is not invited until the end of this post…</p><p>The first thing we do is to load in the data:</p><pre>d3.csv(&#39;planets.csv&#39;, row, function(error, data) { <br>  if (error) throw error; <br> <br>  make(data); </pre><pre>}); </pre><pre>function row(d) { <br>  return { <br>    planet: d.planet, <br>    distance: +d.distance, <br>    radius: +d.radius <br>  }; <br>}</pre><p>We’re loading in our <em>planets.csv</em> piping it through the row() function which makes sure our numbers are indeed numbers. Then we call the make() function, which will be the home of all further code.</p><p>The make() function does the following:</p><ol><li>It sets the dimensions of our visual</li><li>It builds an svg as well as a zoom surface</li><li>It calculates our scales</li><li>It builds our axis</li><li>It builds the planets</li></ol><p>Let’s start with setting our visual’s dimensions.</p><h4>Calculating the dimensions <a href="#3f43">^</a></h4><p>The margin and the height calculations are straightforward:</p><pre>var margin = { <br>  top: window.innerHeight * 0.3, <br>  left: 50, <br>  bottom: window.innerHeight * 0.4, <br>  right: 50 <br>}; </pre><pre>var height = window.innerHeight - margin.top - margin.bottom;</pre><p>We want the svg element to cover our entire screen. So our height will be the window.innerHeight subtracting some margins. We define the top and bottom margin in respect to the window.innerHeight to keep them relative to each other.</p><p>On to the width, which needs just a little more thought:</p><pre>var maxDist = d3.max(data, function(d) { return d.distance; }); </pre><pre>var mapScale = 1/10e4; </pre><pre>// The full width of all planets <br>var chartWidth = maxDist * mapScale; </pre><pre>// svg width will only be as large as screen <br>var screenWidth = window.innerWidth - margin.left - margin.right;</pre><p>The gist of our width calculation is that we want <strong>two</strong> widths. One for the chart and one for the svg. What’s the difference? Well, the chart will be very wide, because it needs to fit all our planets on it. The svg, however, doesn’t need to be very wide. The svg’s task is to show us the planets that fit on our browser window. An svg of the window’s dimensions is henceforth enough. It’ll look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XmI92WJ0jydu2kr-.jpg" /><figcaption>Our chart is wider than our svg</figcaption></figure><p>Note that this is only possible using the zoom behaviour. If we wanted to allow the user to see all planets without the zoom and pan magic, we would need to have an svg as wide as the chart. As a result, the browser would give us scroll bars our users could use to move to the right or left — like in the marvelous <a href="http://joshworth.com/dev/pixelspace/pixelspace_solarsystem.html">If the Moon were only 1 Pixel</a> visual.</p><p>However, using D3 zoom, the zoom transform object we will initialize will keep track of our gestures: how far we “scrolled” to the right, left, and along the z-axis virtually piercing through the screen following our line of sight.</p><p>Based on the transform, we can re-position our elements. And if they happen to be within screen coordinates, they get displayed on our base svg. No harm done if not, they just won’t get shown.</p><p>As such, our svg’s width will get the screenWidth which is just the window.innerWidth minus the margins. How wide will our chartWidth, the base for all planets, be? We will scale down the distance between the two furthest apart orbs (the Sun and Pluto, that is) with our mapScale by 10e4, or 1:10,000. When Pluto is 5,913,000,000 km away from the Sun in real space, it will be 59,130 pixels away from the centre of the Sun in our visual.</p><p>That wasn’t too bad. Onwards!</p><h4>Building out the base</h4><p>First, we build our svg base: a margin-transformed g element dangling off an svg element:</p><pre>var svg = d3.select(&#39;#vis&#39;) <br>  .append(&#39;svg&#39;) <br>    .attr(&#39;width&#39;, screenWidth + margin.left + margin.right)     <br>    .attr(&#39;height&#39;, height + margin.top + margin.bottom)    <br>  .append(&#39;g&#39;) <br>    .attr(&#39;class&#39;, &#39;chart&#39;) <br>    .attr(&#39;transform&#39;, &#39;translate(&#39; + margin.left + &#39;, &#39; <br>           + margin.top + &#39;)&#39;);</pre><p>Then we overlay it with a rect element that we’ll use as our <strong>zoom base</strong>. This rect will listen to all mouse events and gestures, and as such we’ll boldly call it listenerRect:</p><pre>var listenerRect = svg <br>  .append(&#39;rect&#39;) <br>    .attr(&#39;class&#39;, &#39;listener-rect&#39;) <br>    .attr(&#39;x&#39;, 0) <br>    .attr(&#39;y&#39;, -margin.top)<br>    .attr(&#39;width&#39;, screenWidth) <br>    .attr(&#39;height&#39;, height)<br>    .style(&#39;opacity&#39;, 0);</pre><p>Important to note here that our zoom base is at the same spot as the zoom targets — the elements we want to zoom. We will attach our zoom base listenerRect to the svg (which in fact is the margin translated g.chart element as you can see just one code block above), which also be the home of our planet circles we’ll draw later.</p><p>Scales next.</p><h4>Setting up our scales</h4><p>We are mapping two measures to screen coordinates: distance and radius. As such we need two scales. Here’s the first, mapping our planet’s radii in km to screen radii:</p><pre>var rExtent = d3.extent(data, function(d) { return d.radius; }); </pre><pre>var rScale = d3.scaleLinear() <br>  .domain([0, rExtent[1]]) <br>  .range([3, height/2 * 0.9]);</pre><p>First, we get the radius scale. We calculate the domain and map these values to a range of 3px to a little less than half our window’s height, keeping the measures relative to the window.</p><p>Our second scale is the distance scale:</p><pre>var xScale = d3.scaleLinear() <br>  .domain([0, maxDist]) <br>  .range([0, chartWidth]);</pre><p>We map the data extent to the full chartWidth. If you mapped it to the screenWidth, all the planets would stand on their feet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2CJoCvigSTQYZ6rf.jpg" /><figcaption>Too dense</figcaption></figure><p>We could correct this by using a tighter radius scale, but we would like them to stretch out initially and then allow the user to zoom in or out.</p><h4>Drawing the axis</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TM1qj2JwJzJampOv9wg1fw.png" /><figcaption>‘<a href="https://fineartamerica.com/featured/fountain-pen-patent-from-1884-blueprint-aged-pixel.html">Fountain Pen Patent From 1884 — Blueprint</a>’ — by <a href="https://www.agedpixel.com/">Aged Pixel</a></figcaption></figure><p>We’ll be using a normal D3 axis component to build the axis. However, as you can see in the image above, we will stagger the labels so they don’t overlap.</p><p>First, we build out the axis component:</p><pre>var xAxis = d3.axisBottom(xScale) <br>  .tickSizeOuter(0) <br>  .tickPadding(10) <br>  .tickValues(data.map(function(el) { return el.distance; })) <br>  .tickFormat(function(d, i) { <br>    return data[i].planet + &#39; &#39; + d3.format(&#39;,&#39;)(d) + &#39; km&#39;; <br>  });</pre><p>We determine the exact number of tick mark labels by passing an array of the planets’ distance values to .tickValues():</p><pre>[0, 58000000, 108000000, 150000000, 228000000, 778000000,  <br> 1429000000, 2871000000, 4504000000, 5913000000]</pre><p>The axis will now only draw tick labels for these values. We use .tickFormat() to specify what the label will say. In our case, it’ll be <em>&lt;planet name&gt; &lt;distance from sun&gt; &lt;km&gt;</em>.</p><p>Now we produce the axis’ g base and unleash the component on it:</p><pre>var xAxisDraw = svg.insert(&#39;g&#39;, &#39;:first-child&#39;)<br>  .attr(&#39;class&#39;, &#39;x axis&#39;) <br>  .call(xAxis);</pre><p>Like our listenerRect, the axis becomes a child of our g.chart element we labelled svg. Why insert it? We want our zoom base to be on top of all other elements dangling off the svg so it can consume all the events. Looking at the DOM it should be the last child of svg. To achieve this, we’ll insert the axis — and soon the planets — <em>before </em>listenerRect.</p><p>Moving on to our axis labels. By default, all labels will be drawn on the same <em>y</em> level. But we want them staggered, so we need to write some code to achieve the steps. This is the stagger voodoo we apply:</p><pre>// Move the axis-labels and -lines down </pre><pre>var labelHeight = xAxisDraw.select(&#39;text&#39;).node().getBBox().height; </pre><pre>xAxisDraw.attr(&#39;transform&#39;, &#39;translate(0, &#39; + <br>                (height + labelHeight * data.length) + &#39;)&#39;); </pre><pre><br>// Position the axis text </pre><pre>xAxisDraw.selectAll(&#39;text&#39;) <br>  .attr(&#39;y&#39;, function(d, i) { <br>    return -(i * labelHeight + labelHeight); <br>  }) <br>  .attr(&#39;dx&#39;, &#39;-0.15em&#39;) <br>  .attr(&#39;dy&#39;, &#39;1.15em&#39;) <br>  .style(&#39;text-anchor&#39;, &#39;start&#39;);</pre><p>Don’t feel obliged to follow me down this rabbit hole — in short, we move them all down by <em># of labels × their label height</em>. Then we move each label up by <em>their height × their index</em>. As a result, the Sun, for example, won’t move up as it’ll be lifted by <em>0 × labelHeight = 0</em>, but Mercury (the next planet to the Sun) will move up by <em>1 × labelHeight</em> and so on.</p><p>The tick line needs a little more attention, as we have to cater for its <em>y1</em> and <em>y2</em> value:</p><pre>// Draw the axis lines </pre><pre>xAxisDraw.selectAll(&#39;line&#39;) <br>  .attr(&#39;y1&#39;, function(d, i) { <br>    return -(i * labelHeight + labelHeight); <br>  }) <br>  .attr(&#39;y2&#39;, function(d, i) { <br>  <br>    return -(i * labelHeight + labelHeight + from axis-y 0<br>            // ^ this label’s start position<br>   <br>           (data.length-1-i) * labelHeight + <br>            // ^ the distance from the start position <br>            //   to the bottom of the chart area <br>  <br>            height); <br>            // ^ the height <br>   });</pre><p>Good news. We can now draw our planets in (nearly) a single D3 chain:</p><pre>var gPlanets = svg<br>  .insert(&#39;g&#39;, &#39;.listener-rect&#39;)<br>  .attr(&#39;class&#39;, &#39;planet-group&#39;);</pre><pre>var planets = gPlanets.selectAll(&#39;.planet&#39;) <br>    .data(data)<br>  .enter().append(&#39;circle&#39;) <br>    .attr(&#39;class&#39;, &#39;planet&#39;) <br>    .attr(&#39;id&#39;, function(d) { return d.planet; }) <br>    .attr(&#39;cx&#39;, function(d) { return xScale(d.distance); }) <br>    .attr(&#39;cy&#39;, 0) <br>    .attr(&#39;r&#39;, function(d) { <br>      d.scaledRadius = rScale(d.radius); <br>      return d.scaledRadius; <br>    });</pre><p>First, we create a group for all our planets and make sure the listenerRect also covers these planets by inserting our g.planet-group before the rect.listener-rect. Then we join and enter() the data to our as yet virtual .planet&#39;s, which will manifest as circles with the respectively scaled distances as x positions and rScaled radii. So there:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3A9dURmxku3x1292.jpg" /><figcaption>A sensible planetary layout</figcaption></figure><p>Great! We have our visual. Now let’s get to the zoom…</p><h3>Identifying our zoom base and zoom targets <a href="#3f43">^</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bPqnpqTAX5QN7nt8.jpg" /></figure><p>It’s often a wise idea to start by thinking about what you want to do before a head first code plunge. Before setting up our zoom, let’s identify <strong>what</strong> and <strong>how</strong> we want to zoom and pan. We ask 3 questions:</p><ol><li>What will be our zoom base — the “sensor element” that we’ll use for the zoom?</li><li>What will be our zoom targets — the elements that we will move?</li><li>What type of zoom do we want for each element — geometric or semantic zoom?</li></ol><h4>Identifying our zoom base</h4><p>Let’s choose our zoom base element first. You can attach the zoom to an svg, g, rect or any other element that your mouse has access to. Note here that g elements can only register events where they have children with a set fill property. So, if you have a large g element with a circle of radius 1, your zoom gestures will only work on that tiny circle.</p><p>As such, it’s often wise to set up a dedicated rect with fill, but 0 opacity. You have to make sure that the zoom base can consume all events. So, it should either be on top of all other elements, or its pointer-events should be set to all while all other elements’ pointer-events are set to none.</p><p>In fact, we already totally decided to set up an extra rect element to listen to events. We wisely cached it in the listenerRect variable, which we can refer to upon set-up. Done.</p><h4>Identifying our zoom targets</h4><p>Now let’s identify our target elements and write them down. Which elements do we want to move when we zoom and pan? Let’s make a list:</p><ul><li>The planets</li><li>The axis and all their elements (tick lines and tick text only; we’re not showing the axis path).</li></ul><p>Now we know our zoom base and our targets, we want to make sure they share the same coordinate system at the initial zoom state — when no zoom or pan has happened yet. That’s why we attached the zoom base and targets (planets, axis) to the same g above.</p><p>This is going really well!</p><h4>Identifying the type of zoom</h4><p>Lastly, let’s decide <strong>how</strong> we want to zoom them — geometrically or semantically? First of all, this distinction only makes sense for zooming, not panning. We’ve defined it above, but for the purpose of redundant completeness, let’s repeat that Geometric zoom is simple: all elements are just being scaled up or down uniformly. Semantic zoom is a little more elaborate, as you can decide what you want to scale up or down.</p><p>In our case, we might want to scale up the size of the planets, but keep the line width at 4px. For that we would need semantic zoom. For our educational purposes, let’s implement both types! Why not?</p><h4>Setting up the zoom</h4><p>For any zoom we decide to implement, we will need to set it up first. You’ll probably agree that it couldn’t be less complex:</p><pre>var zoom = d3.zoom() .on(&#39;zoom&#39;, zoomed);</pre><p>Calling d3.zoom() will return an object and a function. As with many parts of the D3 API, the object allows us to configure the variables we use in the function. So what we do up there is configure the use of the d3.zoom() function with a single method: .on() attaches a handler function called zoomed. zoomed will be called every time we zoom. This is where we’ll make the elements move.</p><p>We have two other zoom cycle events to trigger a function, start and end. It should be relatively easy to guess when they would trigger the callback.</p><p>We store the returned function in the creatively named variable zoom. Next, we can use this function as zoom(&lt;listener-element&gt;) or, as it’s more commonly done in D3 &lt;listener-element&gt;.call(zoom) like so:</p><pre>listenerRect.call(zoom);</pre><p>That’s great, but what does that mean? It means that the listenerRect is now the official home of our zoom. Our <strong>zoom base</strong>! At this very moment, it has two things dangling off it: the .on() event and the zoom transform. If we console.dir(d3.select(‘#listener-rect’).node()) and check our attributes, we’ll find these two D3 properties at the very bottom of the list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/0*pBCBMOomXIXAB63l.jpg" /></figure><p>The __on object holds our listener information, and the __zoom object is a transform object holding the 3 values we discussed in the beginning of this pot: the <em>x</em> and <em>y</em> translation when we zoom and pan, and the scale factor <em>k</em> changing upon zoom.</p><p>You can always come to your zoom base — the listenerRect for us — to query the current transform values. However, you don’t need to do so very often, as the transform will be handily accessible in the event object from within our zoomed handler function. Right. For the love of our lives — let’s finally zoom.</p><h3>Geometric zoom with SVG</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*8TcSFFsDuP9kKj37gOpPqQ.png" /><figcaption>‘<a href="https://fineartamerica.com/featured/microscope-patent-from-1886-blueprint-aged-pixel.html">Microscope Patent From 1865 — Blueprint</a>’ by <a href="https://www.agedpixel.com/">Aged Pixel</a></figcaption></figure><p>We have our static visual. We’ve set up the zoom. We’ve attached it to the zoom base. Let’s finally decide which type of zoom we’re going for. Here’s the thing: axes should be zoomed semantically, you decide for the other elements. Going back to our zoom targets, let’s decree this here in a table on a piece of parchment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/0*stMMbWj0THZA_A6G.jpg" /></figure><p>Now, let’s write the zoom handler:</p><pre>function zoomed() { </pre><pre>  var transform = d3.event.transform; </pre><pre>  gPlanets.attr(&#39;transform&#39;, transform.toString()); </pre><pre>}</pre><p>We’re not quite done yet, but this is the simplest zoom possible and will already move our planets. We cache the transform object that dangles off the d3.event object which gets passed in on every zoom and pan move in the variable transform. Then we move our planets by just updating the transform attribute of our circles.</p><p>transform.toString() is just a convenience method the transform object gives us. It saves us from having to type out the transform attribute’s value. For the identity transform { k: 1, x: 0, y: 0 } it returns the string &quot;translate(0, 0) scale(1)&quot;</p><p>How will this look?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*HeMf3jBM6CCDY7ZE.gif" /><figcaption>Super! The planets move (all over the shop)</figcaption></figure><p>Very good! The planets are moving — the rest is not. We need to do 3 things to improve this:</p><ol><li>Let’s prohibit the planets from moving to the right (there’s no planet left of the sun, so it would be futile).</li><li>Let’s also prohibit the planets from moving up and down.</li><li>Move the scales.</li></ol><p>1 and 2 are simple; we just manipulate the transform object before we use it like so:</p><pre>function zoomed() { </pre><pre>  var transform = d3.event.transform; <br>  <br>  transform.x = Math.min(0, transform.x); <br>  transform.y = 0; </pre><pre>  gPlanets.attr(&#39;transform&#39;, transform.toString()); </pre><pre>}</pre><p>As a result, <em>x</em> is never higher than 0, and therefore we can’t move the thing to the right. Also, <em>y</em> will always be 0. The result does what we expect:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*etC92L78JfRodZLh.gif" /><figcaption>The planets move (..only over the sensible shop parts)</figcaption></figure><p>Next, let’s make the axis move semantically. Our axis consists of labels and lines. We choose semantic over geometric zoom, as we only want to change their <strong>position</strong> on zoom — not the label size or the line width.</p><p>The main positioning engine behind the axis’ elements — the thing that makes the labels and lines move — is the scale. And what does the scale do? The scale maps our data values to the width of our svg element. If we want to change a scale with D3, we usually update the scale’s domain and/or range. But as rescaling axes is such a common activity for D3 zoom, we have the rescaleX() and rescaleY() methods dangling off the transform object. It updates the mapping for us according to the zoom. Perfect syntactic sugar we can use to create an updated scale:</p><pre>var xScaleNew = transform.rescaleX(xScale);</pre><p>The next section is called <em>Semantic Zoom with SVG</em> and will carelessly open the hood of this rescaleX() method in much more detail. But for now, let&#39;s just use xScaleNew trustingly like so:</p><pre>xAxis.scale(xScaleNew); xAxisDraw.call(xAxis);</pre><p>We update the scale of our xAxis and redraw the axis with our new axis component. The last thing we need to do to the axis is stagger our labels and lines again, as we’ve done above.</p><pre>// Stagger the axis-labels <br>xAxisDraw.selectAll(&#39;text&#39;) <br>  .attr(&#39;y&#39;, function(d, i) { <br>    return -(i * labelHeight + labelHeight); <br>  }) </pre><pre>// Stagger the axis-lines <br>xAxisDraw.selectAll(&#39;line&#39;) <br>  .attr(&#39;y1&#39;, function(d, i) { <br>    return -(i * labelHeight + labelHeight); <br>  }) <br>  .attr(&#39;y2&#39;, function(d, i) { <br>    return -(i * labelHeight + labelHeight <br>           + (data.length-1-i) * labelHeight + height); <br>  });</pre><p>Remember, all of this happens in our zoomed handler.</p><p>It works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*4cXO4FJVGHthyWlG.gif" /><figcaption>Geometric zoom with SVG <a href="https://bl.ocks.org/larsvers/95115f57fb67ac8c0a568fdd28ae8c00">with</a> and <a href="https://bl.ocks.org/larsvers/raw/95115f57fb67ac8c0a568fdd28ae8c00">without code</a></figcaption></figure><h3>Semantic zoom with SVG</h3><p>This headline comes a bit late. We have semantically zoomed our axis already. But now let’s also apply it to our planets and dive into the rescaling process. Here’s our updated prep table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/0*Exu-fOwyKUh9WLrV.jpg" /></figure><h4>Semantic zoom of circles</h4><p>First of all, why would we want to use semantic zoom on the planets? I guess the above gif demonstrates the semantic need pretty well. As the planets get smaller, their outline is nearly impossible to see. With semantic zoom, we will have control over which element properties change or remain. In our case, zoom should change the position as well as the size of our planets, but the width of the outline stroke should stay constant at 4px.</p><p>What we do is simple:</p><pre>function zoomed() { </pre><pre>  var transform = d3.event.transform; </pre><pre>  transform.x = Math.min(0, transform.x); </pre><pre>  var xScaleNew = transform.rescaleX(xScale); </pre><pre>  planets <br>    .attr(&#39;cx&#39;, function(d) { <br>      return xScaleNew(d.distance); <br>    })<br>    .attr(&#39;r&#39;, function(d) { <br>      return d.scaledRadius * transform.k; <br>    }); </pre><pre>  // Zoom and pan the axis here (…) </pre><pre>}</pre><p>First, we remove our geometric planet zoom. Then we grab our planets and, instead of transforming them, we specifically only access their cx and the r attributes. The <em>x</em> position will be re-calculated with the updated xScaleNew and the radius just needs to be multiplied by the scale factor. No translation necessary here.</p><p>And that’s it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*dtM5kL52kfFuQ4G0.gif" /><figcaption>Semantic zoom with SVG <a href="https://bl.ocks.org/larsvers/1333b243c89809d39290e42bb3d79924">with</a> and <a href="https://bl.ocks.org/larsvers/raw/1333b243c89809d39290e42bb3d79924">without code</a></figcaption></figure><p>However far we zoom in or out, our stroke remains at 4px allowing us to actually see our planets even if they’re fully zoomed out.</p><h4>Understanding zoom rescale</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*VQ1h-qEW-PkMUUR61WXYOQ.jpeg" /><figcaption>some non-related scales</figcaption></figure><p>Semantic zoom requires us to zoom and pan properties selectively. Our semantic planet zoom above only changed the cx and the r attribute, while keeping the stroke width at 4px. To specifically change cx, we needed to update our scale — the main positioning engine of our visualisation — so that it positions our elements according to the new transform.</p><p>As said, D3 offers the convenience methods rescaleX() and rescaleY() to update scales according to the transform. Of course it’s perfectly fine to use these methods without knowing the inner workings, so please feel free to jump straight to <a href="#6867">the next section</a>. But if you’re curious about how exactly the rescale happens, stay with me. There&#39;ll be images in color, too.</p><p>We’ll use a real simple example. Let’s assume we only look at the x-dimension, and we want to map a data space that covers a domain from 0 to 100 to a 1000 pixel wide screen. As such we have a data domain of [0, 100] we want to map to a width range of [0, 1000]. Our scale would look like this:</p><pre>var xScale = d3.scaleLinear() <br>  .domain([0, 100]) <br>  .range([0, 1000]);</pre><p>Let’s also assume that we have a single circle with the data value 20, which would be mapped to the pixel value 200:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BotW8zQlDpbV8Cdw.jpg" /></figure><p>Easy. Now we zoom in so that our scale factor <em>k</em> will be 2. No translation, just zoom. As a result, our circle would move according to our zoom transform formula we started this post with: <em>tx + x × k</em>, which would result in <em>0 + 200 × 2 = 400</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iyqvhq4hKKOlGIJJ.jpg" /></figure><p>Note, we’ve also scaled up its radius by 2. All good so far? Great.</p><p>In this case, we could just do our transform calculation for the circle. But it’s much simpler, more convenient, and more consistent to continue to use our scale. However, we need to update it, as our data value 10 shouldn’t scale to 100px anymore but to 200px!</p><p>How do we do this? As we’ve done above, we just pass our xScale to the transform.rescaleX() function. This returns the respectivley updated newXScale, which we use on the circle’s data value to determine the cx position:</p><pre>var newXScale = transform.rescaleX(xScale); </pre><pre>circle.attr(‘cx’, function(d) { return d.dataValue; }); <br>// note: d.dataValue is from a fictitious dataset</pre><p>But what exactly does this rescale do? Let’s look at the <a href="https://github.com/d3/d3-zoom/blob/master/src/transform.js#L33">source</a> <a href="https://github.com/d3/d3-zoom/blob/master/README.md#transform_rescaleX">code</a> first before considering its logic. A rescale under the hood looks like so:</p><pre>function rescaleX(x) { </pre><pre>  var range = x.range().map(transform.invertX, transform), </pre><pre>  domain = range.map(x.invert, x); </pre><pre>  return x.copy().domain(domain); </pre><pre>}</pre><p>As you can see in the last line, it will return the original scale <strong>BUT</strong> with an updated domain. The range will remain as is. If you asked me before I looked at this code, I would’ve guessed D3 would update the range and keep the domain as is. Much more direct. But it’s the other way around. This makes sense, as the pixel range is a more static concept. In our case, 1000 is the width of the screen — that won’t change upon zoom.</p><p>The (small) downside is that the new domain calculation is slightly more involved than a new range calculation would be. There are 4 steps involved in calculating the new domain at each zoom and pan move:</p><ol><li>We first take the range of our original scale. In our example that would be [0, 1000].</li><li>We then apply the inverse transform to it, which will return [0, 500].</li><li>Next we will use the scale’s .invert() method to find the data value associated with the range values 0 and 500, which will be [0 and 50] in our case.</li><li>Finally, we override the current x-scale domain with this new domain and return it.</li></ol><p>But why? Let’s consider this conceptually…</p><p>First, we calculate a new range by taking the inverse of our transform function for the <em>x</em> value. By now we know the zoom transform function for <em>x is tx + x × k</em>. Its inverse is <em>(x — tx) / k</em>.</p><p>If you never came across inverse functions, they are just the opposite — the reverse of their main function. If you had <strong>f(x) = 3 × x</strong> then the inverse is <strong>g(y) = y/3</strong>. Plugging 2 into the main function <strong>f(x)</strong> returns 6 — plugging this 6 into the inverse function <strong>g(y)</strong> returns 2 again. It reverses the process of the main function.</p><p>Why do we take the inverse on our range? We want to adjust the domain, but keep the range at [0, 1000]. The easiest way to get the updated domain is to first calculate updated range extent values (min and max) in order to derive the new domain extent values from them.</p><p>Let’s play this through with a single value. Let’s take our maximum range value of 1000. Our current scale maps the maximum data value of 100 to the maximum range value of 1000 pixels.</p><p>What’s the max range value when we scale by 2? Scaling by 2 means we’re zooming in. So, our current max range value of 1000 will move to 2000 <em>(0 + 1000 × 2)</em>. However, we would like to know the new pixel point that moves to the edge of our screen when we zoom. The previous point that was at 1000 and is now at 2000 is no help to us as it’s beyond the screen area now. So, which point is at the edge of our window after we zoomed? Which point is our new maximum range value?</p><p>In order to get that point, we don’t ask: where does our current max range value of 1000 zoom to? We ask, where does the new max range value come from! Logically, this is the opposite or the <strong>INVERSE</strong> question. Accordingly, we apply the inverse zoom transformation: <em>(x — tx) / k</em>. We plug in our previous max range value of 1000px, our <em>tx</em> of 0 and scale <em>k</em> of 2 to get: <em>(1000–0) / 2 = 500</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7k_kT0hlNqus0tX_.jpg" /></figure><p>We can now say that our new maximum range value would come from the pixel position 500.</p><p>Why did we do this again? Isn’t this all a bit silly as we want to keep the range at [0, 1000] anyway? Yes. And no. It’s not silly, because we don’t use this new maximum range value in a new range input for our scale. We just use it to find our new maximum data domain value.</p><p>We take our original scale that mapped a data value of 0 to 0 pixel, a data value of 100 to 1000 pixel and all in-between values accordingly. Now we ask which data value maps to the pixel value of 500? For this simple case we can use our brain, or — much better — we use the .invert() method of our original x-scale. xScale.invert(500) will return 50 as probably expected.</p><p>Let’s remember here that we still have our original range of [0, 1000]. All the range calculations we have done were only done in order to get to the new domain. Our new x-scale still maps the data value 0 to pixel 0, but now maps the new maximum data domain value of 50 to the loyally standing maximum range value of 1000.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vrbN6jONhhLdy03_.jpg" /></figure><p>Likewise, our circle center x value still has the data value of 10, which now doesn’t map to 100 but to 200. We successfully zoomed in, we did.</p><p>Well done! Now, onwards to Canvas. Same game — different board…</p><h3>Geometric zoom with Canvas <a href="#102a">^</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*SuRUQKKLEfRKDHW1Bwqlnw.jpeg" /></figure><p>We only have 10 circles on our site. However, there are of course a great many more orbs out there to visualize. Visualizing more than 1000 of them might get you into render performance troubles, which you can attempt to cure with Canvas.</p><p>Unlike SVG, Canvas produces a single bitmap of your drawing. 1000 planets on your screen will be drawn to a single DOM element, the canvas. In SVG 1000 planets will produce 1000 circle elements that the browser has to maintain, which affects performance. There’s a list of Canvas resources in the <a href="#28f2">sources</a> section below if you want to know more, but don’t worry, you don’t need a Canvas degree to follow along.</p><p>We will change very little in our app. As a quick reminder, here are the main steps we’ve folowed to get here:</p><ol><li>Load data</li><li>Calculate the dimensions of our visual</li><li><strong>Build the SVG base and the listener rectangle</strong></li><li>Calculate the scales</li><li>Define and draw the axis</li><li><strong>Build the SVG visual</strong></li><li><strong>Zoom</strong></li></ol><p>We’ll change points 3, 6 and 7 above and leave the rest unchanged. In fact, we won’t produce a pure Canvas drawing, but rather will draw the planets in Canvas and keep the axes in SVG. This is called <strong>Mixed-mode rendering,</strong> and is really clever if you have axes to draw. Drawing axes is wonderfully solved by D3 in SVG but can be a pain in Canvas. (<a href="https://medium.com/u/b8fe3c1518c1">Elijah Meeks</a> dedicates a good section to Mixed-mode rendering in chapter 11 of his book <a href="https://www.manning.com/books/d3-js-in-action">D3js in Action</a>)</p><h4>Adding a canvas base</h4><p>As with SVG, we need a base to draw on. For Canvas we need two things, the canvas element and its drawing context — the tools we can use to draw on the canvas. Below our svg base we add the following Canvas base snippet:</p><pre>var canvas = d3.select(&#39;#vis&#39;).append(&#39;canvas&#39;) <br>  .attr(&#39;width&#39;, screenWidth + margin.left + margin.right)   <br>  .attr(&#39;height&#39;, height + margin.top + margin.bottom); </pre><pre>var context = canvas.node().getContext(&#39;2d&#39;);</pre><p>It’s often wise to skip the margin convention for Canvas (we don’t have a g we can move around). But, especially when drawing SVG axes, we want to cling on to our margins.</p><p>We also want to overlay our canvas element perfectly over our svg element and its children, the planet g and the listenerRect. To achieve this, we need to give it the same size as the svg element and position the canvas absolute on top of the svg. Here’s our CSS:</p><pre>canvas { <br>  position: absolute; <br>  top: 0; <br>  left: 0; <br>  pointer-events: none; <br>}</pre><p>Notice that we also remove all pointer-events from our canvas so that the listenerRect receives all gestures. As a result, we have quite a few layers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Io-B2lxm6R9G6bKS.jpg" /><figcaption>Our layer cake with SVG axis and Canvas planets</figcaption></figure><p>The g now only holds our axis, which we can view through our svg. The canvas will display our planets, but only the section in green above (the other planets are drawn here for completeness but will initially be invisible). The top level is the listenerRect consuming all pointer events and informing our zoom and pan.</p><h4>Drawing the planet circles in Canvas</h4><p>We remove the logic that built out the SVG planets, and instead draw our Canvas circles. We will draw it in a single function. Let me first show you the code of this Canvas drawing function before running you through it. Here we go:</p><pre>function drawGeometricCircles(data, transform) {</pre><p>We pass our data and the transform. If we only wanted to build a static visual we wouldn’t need to worry about the transform, but zooming is very much our mission!</p><pre>  context.clearRect(0, 0, screenWidth + margin.left + margin.right,   <br>                    height + margin.top + margin.bottom);</pre><p>Next, we access our Canvas context (we cached in the context variable) and run a method called .clearRect. You can surely guess what it does — it clears the canvas. We pass it the canvas dimensions, which will clear the canvas every time we call this function.</p><p>This is what we do with Canvas. Unlike in SVG where we have manifest nodes in the DOM for our circles, we only have a pixel image on our canvas. Instead of moving around a DOM node, we just remove the image we drew earlier and draw a new image with elements in slightly different positions. That’s Canvas for you.</p><pre>  context.save();</pre><p>Then we .save() the default and unchanged context, and we .restore() it in a moment after all drawing is done. This way we secure not only a blank canvas slate, but also a blank context slate whenever we draw a new planet.</p><pre>  context.lineWidth = 4; <br>  context.strokeStyle = &#39;deeppink&#39;; <br>  context.fillStyle = &#39;white&#39;;</pre><p>Next, we define our painting brushes. We want a line width of 4px, we want a stroke color of deeppink and a fill of white. These aesthetic properties will apply to everything we draw after we set them. Until we change them.</p><pre>  context.translate(transform.x + margin.left, margin.top);     <br>  context.scale(transform.k, transform.k);</pre><p>These next two lines are the geometric zoom. We translate and scale the entire image we draw by the respective transform values.</p><pre>  for (var i = 0; i &lt; data.length; i++) {</pre><pre>    context.beginPath();<br>    context.arc(xScale(data[i].distance), 0, <br>                rScale(data[i].radius), 0, 2 * Math.PI, false); <br>    context.stroke(); <br>    context.fill(); </pre><pre>    context.fill(); </pre><pre>  } </pre><pre>  context.restore(); </pre><pre>}</pre><p>Finally, we draw the circles. If you haven’t seen much of Canvas yet, this might look a little raw. And indeed, D3 internalizes this loop through the elements for us by joining the data to selections that we can subsequently access, position, and style.</p><p>With Canvas, we do this ourselves. We loop through the data, start a path, draw the path as a circle with the context.arc() method, and finally stroke and fill the path.</p><p>The rest is a piece of code. We just need to call it right here, and then with our data and the identity, transform, which is simply { k: 1, x: 0, y: 0 }:</p><pre>drawGeometricCircles(data, d3.zoomIdentity);</pre><p>Whenever we zoom, we replace the code that moved our SVG planets with this:</p><pre>drawGeometricCircles(data, transform);</pre><p>I’ll spare you the gif as it looks exactly like what we’ve seen above with geometric SVG zoom. But the working implementation with code is just <a href="https://bl.ocks.org/larsvers/6f4305086c832298167a2334e3c68990">a click away</a>!</p><h3>Semantic zoom with Canvas</h3><p>Let’s celebrate our geometric zoom feat by getting rid of it. In fact, to achieve semantic instead of geometric zoom, we will just rename and change our draw function. We will call it appropriately drawSemanticCircles().</p><p>Changing from geometric to semantic zoom in Canvas requires the same high-level actions. Instead of translating and scaling the planet’s coordinate system, we will change the planet’s positions and radius according to the transforms.</p><p>drawSemanticCircles() will clear our canvas and then draw all circles with drawCircle():</p><pre>function drawSemanticCircles(data, transform) { </pre><pre>  context.clearRect(0, 0, screenWidth + margin.left + margin.right, <br>                    height + margin.top + margin.bottom); </pre><pre>  for (var i = 0; i &lt; data.length; i++) { <br>    drawCircle(data[i], transform); <br>  } </pre><pre>}</pre><p>drawCircle() will be run for each data element, taking the data element and the current transform:</p><pre>function drawCircle(elem, transform) { </pre><pre>  var x = (transform.x + transform.k * xScale(elem.distance))<br>           + margin.left;<br>  var y = margin.top; <br>  var r = transform.k * rScale(elem.radius); </pre><pre>  context.lineWidth = 4; context.strokeStyle = &#39;deeppink&#39;;   <br>  context.fillStyle = &#39;white&#39;; </pre><pre>  context.beginPath(); <br>  context.arc(x, y, r, 0, 2 * Math.PI); <br>  context.stroke(); <br>  context.fill(); </pre><pre>}</pre><p>We first determine the <em>x</em> and the <em>y</em> positions as well as the radius <em>r</em>. Then we define the styles for our circles. Lastly, we draw our galactic spheres as arcs. And that’s it…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DbVcQpD2jIaxpxA4.gif" /><figcaption>Semantic zoom in Canvas <a href="https://bl.ocks.org/larsvers/32f2ef58c910e1d4ada8a462f7474b75">with</a> and <a href="https://bl.ocks.org/larsvers/raw/32f2ef58c910e1d4ada8a462f7474b75">without code</a></figcaption></figure><p>Great! We’ve covered the two types of zoom in two renderers. On to the bonus tracks: programmatic zoom and making our galaxy pretty…</p><h3>Programmatic zoom</h3><p>It’s often helpful to move our visuals into a certain position. You can let a user center a map, move a long bar chart to the beginning, or zoom in and out of the solar system.</p><p>We have neither a map nor a bar chart, so let’s programmatically zoom out and back into our planets upon load. We go back to SVG for this, as we don’t really need Canvas here. Because of its lower level, I’d recommend using Canvas only if you need it or speak it like your mother tongue. As we only have 10 circles to move around here, we don’t need it.</p><p>Here’s what we want to achieve:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*SFFjZshJiDJkEVIZ.gif" /><figcaption>Programmatic zoom in SVG <a href="https://bl.ocks.org/larsvers/4b39be68e8cb77e7c402bd96df292db0">with</a> and <a href="https://bl.ocks.org/larsvers/raw/4b39be68e8cb77e7c402bd96df292db0">without code</a></figcaption></figure><p>We start with a heavily zoomed-in visual at a zoom scale of 20. We then zoom out to our minimum zoom, so all planets fit comfortably on the page. Lastly, we zoom back in to our default zoom scale of 1.</p><p>To achieve this, we bolt on the programmatic logic to the bottom of our make() function where all our app code lives. We start by zooming in to a scale factor of 20 without panning:</p><pre>var initialTransform = d3.zoomIdentity.scale(20); listenerRect.call(zoom.transform, initialTransform);</pre><p>d3.zoomIdentity returns the identity transform we have already encountered a few times. We change the transform scale to 20 and cache it in initialTransform. Then we use the zoom.transform() function. This function is obviously different from our transform object, but it directly manipulates it. We use it here with D3&#39;s own &lt;selection&gt;.call() method we encountered above. The selection we call zoom.transform() on will be its first argument. It will be our zoom base listenerRect, home to our current transform object. The second argument has to be a new transform object. It will replace the current transform on that node.</p><p>The cherry on top is that instead of passing our zoom base as a simple selection, we can pass it as a transition. Remember (or note) that transitions are just derived selections, so passing in listenerRect.transition() will in fact transition our visual from one transform to the other.</p><p>But so far, we’ve just snapped our visual to a scale of 20. Let’s kick off the transition. First to a scale of minZoom we have defined earlier, then to a scale of 1. Here’s what we do:</p><pre>// Trigger programmatic zoom <br>progZoom()</pre><p>Let’s write it. It won’t take any arguments:</p><pre>function progZoom() {</pre><p>We first define the transform for the minZoom we want to zoom to first:</p><pre>var zoomOutTransform = d3.zoomIdentity.scale(minZoom);</pre><p>In the following lines, we turn our listenerRect into a transition and call zoomTransform() again. Using .call() we pass in the transition we just built as a first argument and zoomOutTransform — the minZoom transform we just saved:</p><pre>listenerRect <br>  .transition() <br>  .duration(5000) <br>  .call(zoom.transform, zoomOutTransform) <br>    .on(&#39;end&#39;, zoomToNormal)</pre><p>At the end of the zoom we call a function called zoomToNormal. It does exactly what we just have done, apart from transition-zooming to an identity transform:</p><pre>function zoomToNormal() { <br>  listenerRect <br>    .transition() <br>    .duration(3000) <br>    .ease(d3.easeQuadInOut) <br>    .call(zoom.transform, d3.zoomIdentity) <br>}</pre><p>Apart from zooming to a different transform, we’re also setting a different duration as well as a different easing function.</p><pre>}</pre><p>And that was our first bonus track. On to track two…</p><h3>Making our visual pretty</h3><p>It’s wise to get your visuals right in black and white first (pink and white in our case). But in the end, a lick of paint can’t hurt. In order to get here…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*_iW-_i5b3HvPizuR.gif" /><figcaption>Our final app <a href="https://bl.ocks.org/larsvers/c894849af45ce94dc85d76467980f922/">with</a> and <a href="https://bl.ocks.org/larsvers/raw/c894849af45ce94dc85d76467980f922/">without code</a></figcaption></figure><p>…we only need to change a few things, of which the planet’s glow is probably the most elaborate. Let’s look at the rest first:</p><p>We’ll add a dark blue background with a radial gradient moving into the dark blue from a slightly lighter one. It’s one line in our body CSS:</p><pre>body { <br>  font-family: Avenir, sans-serif;<br>  sans-serif; <br>  font-size: 0.75rem; <br>  margin: 0; <br>  <strong>background: radial-gradient(#091C33, #091426);</strong> <br>}</pre><p>We change the text and line colour to a grey off-white (#ddd), and instead of the solid lines, we render dashed lines with wide gaps:</p><pre>.tick line, .lines { <br>  stroke: #ddd; <br>  stroke-width: 0.5; <br>  shape-rendering: crispEdges; <br>  stroke-dasharray: 1,5; <br>}</pre><p>Lastly, we fill the planets with our favourite deeppink and add the glow. The glow is an SVG filter we apply to each planet. I won’t go into detail here, but you can find the code commented <a href="https://github.com/larsvers/Understanding-Zoom/blob/master/zoom_step_07.html#L165-L207">right here</a>. In short, we thicken the planets a little bit before feathering them with some Gaussian blur. We fill the blur deeppink and marvel at the resulting glow. The filter gets an id of #soft-glow, which our planets can reference with the filter attribute:</p><pre>var planets = gPlanets.selectAll(&#39;.planet&#39;) <br>    .data(data)<br>  .enter().append(&#39;circle&#39;) <br>    .attr(&#39;class&#39;, &#39;planet&#39;) <br>    // (…) <br>    .attr(&#39;filter&#39;, &#39;url(#soft-glow)&#39;);</pre><p>And that’s it!</p><p>We’ve come a long way, and hopefully you now understand D3 zoom a little better. We’ve looked into a short recipe you can follow before and during wiring your visual up with any zooming and panning. We then applied this blueprint to a real project with pink orbs, playing through geometric and semantic zoom rendering in SVG as well as Canvas. As a bonus, we looked at programmatic zoom and finally made its subtly pink face even more pink. What fun!</p><p>Two more things that might help: a quick note on updating your zoom from D3 v3 to v4, and a list of sources.</p><h3>Updating zoom from v3 to v4</h3><p>In 2016 (as in many generations ago) D3 v4 superseded v3 with some great but breaking changes. Some conceptual changes including the zoom behaviour kept devs up at night (including myself). The changes are consistent and sensible, but are worth a few extra notes that might help you find sleep:</p><ul><li>As with v3, zoom in v4 is just about the x and y translation and the scale — the transform parameters. That is, of course, brutally simplifying complexity, but it’s a mantra you should try out when gridlocked.</li><li>The transform parameters are stored with the zoom base in v4, while they were stored with the behavior in v3. The behavior now just passes the transform on to the targets. This is good to know when we want to retrieve the transform outside of the zoom handler.</li><li>The v3 behaviour rescaled your scale automatically. In v4 you need to rescale your scale in the zoom function manually, and update all scale-based shapes and components. This is a little more work, but significantly less magic and a clearer separation of concerns.</li></ul><h3>Sources <a href="#07df">^</a> <a href="#7362">^</a></h3><p>There is no abundance of D3 (v4) zoom related posts and tutorials out there. The lack thereof was one reason to write this tutorial. However, there are a few zoom gems as well as some helpful further Canvas related material you can have a look at:</p><p>Article additions:</p><ul><li><a href="https://github.com/larsvers/Understanding-Zoom">GitHub repo for all code we went through in this article</a></li><li><a href="https://bl.ocks.org/larsvers/93b2f692217845d51fc75cd43c029303">All the steps we took above as working apps with code</a></li></ul><p>Zoom tutorials:</p><ul><li><a href="http://emptypipes.org/2016/07/03/d3-panning-and-zooming/">Zoom explained by Empty Pipes</a></li><li><a href="http://www.puzzlr.org/zoom-in-d3-v4/">Zoom explained by Puzzlr</a></li><li><a href="https://swizec.com/blog/two-ways-build-zoomable-dataviz-component-d3-zoom-react/swizec/7753">Zoom with React and D3</a></li></ul><p>Zoom tech:</p><ul><li><a href="https://bl.ocks.org/mbostock/3680958">Mike Bostock’s zoom examples</a></li><li><a href="https://infovis-wiki.net/wiki/Semantic_Zoom">Geometric vs Semantic Zoom</a></li><li><a href="https://github.com/d3/d3-zoom">D3 v4 Zoom API Referene</a></li></ul><p>Canvas:</p><ul><li><a href="https://medium.freecodecamp.org/d3-and-canvas-in-3-steps-8505c8b27444">D3 and Canvas (shameless self-reference)</a></li><li><a href="https://www.visualcinnamon.com/2015/11/learnings-from-a-d3-js-addict-on-starting-with-canvas.html">More D3 and Canvas</a></li><li><a href="https://bocoup.com/blog/2d-picking-in-canvas">And even more D3 and Canvas</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*oFinMnitD5AzlZ3FLLp71Q.jpeg" /></figure><p>I truly hope you enjoyed reading this. Please clap if you want to spread the word, follow me on <a href="https://twitter.com/lars_vers">Twitter</a> and <a href="/service/mailto:lars@datamake.io?Subject=Hello">do say hello</a> to either just say hello or tell me about other ways to zoom.</p><p>Knowledge is partial and we’re all here to learn…</p><p><em>Originally published at </em><a href="http://www.datamake.io/blog/d3-zoom"><em>www.datamake.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d963b0a153e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/get-ready-to-zoom-and-pan-like-a-pro-after-reading-this-in-depth-tutorial-5d963b0a153e">D3 zoom — the missing manual</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing the Data Visualization Community Survey 2017]]></title>
            <link>https://medium.com/free-code-camp/introducing-the-data-visualization-community-survey-2017-7c41e2b3ca9c?source=rss-3ed15968ada5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c41e2b3ca9c</guid>
            <category><![CDATA[design]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[community]]></category>
            <dc:creator><![CDATA[lars verspohl]]></dc:creator>
            <pubDate>Sat, 04 Mar 2017 20:26:27 GMT</pubDate>
            <atom:updated>2017-03-05T09:06:23.704Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WjQFbFd4TbWOmO0wdiO7Eg.png" /></figure><p>Data visualization is a funny fish. It sort of stands on its own feet (or fins), but is also intimately entangled with other disciplines like statistics, machine learning, data engineering, front-end development, and design. Its creations are equally varied, ranging from the all-mighty bar chart to full-on data art.</p><p>This means that data visualization skills are in demand from all sorts of neighbouring disciplines. But it also means that data visualization is poorly understood by budget and decision makers, who may see it as a nice-to-have that requires justification.</p><p>The <a href="https://docs.google.com/forms/d/e/1FAIpQLSdafREbGORZkPTeL8iU7chb5D9thcG-zE2kF7geOwRmy_Y8Hg/viewform?c=0&amp;w=1"><strong>Visualization Community Survey 2017</strong></a> tries to build a base to better understand the people working in the field, how they work, and what their problems are.</p><p>The general goal is to get a better picture of the field of data visualization itself, where it stands, and where it’s headed. More specifically it should help community discussions about what practitioners need so they can argue their corner or further their work.</p><p>Whether you produce data visualizations as just one part of your job, or you spending 120% of your work day on it, you are a valuable voice in this.</p><p><strong>So pretty please, if you have 10 minutes spare, head over to…</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdocs.google.com%2Fforms%2Fd%2Fe%2F1FAIpQLSdafREbGORZkPTeL8iU7chb5D9thcG-zE2kF7geOwRmy_Y8Hg%2Fviewform%3Fembedded%3Dtrue&amp;url=https%3A%2F%2Fdocs.google.com%2Fforms%2Fd%2Fe%2F1FAIpQLSdafREbGORZkPTeL8iU7chb5D9thcG-zE2kF7geOwRmy_Y8Hg%2Fviewform%3Fc%3D0%26w%3D1&amp;image=https%3A%2F%2Flh6.googleusercontent.com%2F4SA_VWT163xCqtUeOrDxYDsdiawP6OC-1pTx6093HkANRd9ghIKo3Ocln1H1dRvH3lE%3Dw1200-h630-p&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=google" width="760" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/94dbad8046814eb4147cc0b948119524/href">https://medium.com/media/94dbad8046814eb4147cc0b948119524/href</a></iframe><p><strong>…and fill it in and help spread the word with a like </strong><em>💚</em></p><p>The survey is completely anonymous. We’ll release the results on Github, so everyone can help analyze/shape/visualize the results.</p><p>Thank you !</p><p>PS: the survey is a result of community discussions on Twitter, Slack, and elsewhere, with many individuals involved. Survey questions and the final draft are based on community efforts and edited by <a href="https://medium.com/u/b8fe3c1518c1">Elijah Meeks</a> and others.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c41e2b3ca9c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/introducing-the-data-visualization-community-survey-2017-7c41e2b3ca9c">Introducing the Data Visualization Community Survey 2017</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[D3 and Canvas in 3 steps]]></title>
            <link>https://medium.com/free-code-camp/d3-and-canvas-in-3-steps-8505c8b27444?source=rss-3ed15968ada5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8505c8b27444</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[3d]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[lars verspohl]]></dc:creator>
            <pubDate>Sat, 18 Feb 2017 05:32:17 GMT</pubDate>
            <atom:updated>2017-05-21T22:39:14.763Z</atom:updated>
            <content:encoded><![CDATA[<h4>The bind, the draw and the interactivity</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KCOutWkXvU7YhGY2f76kfQ.jpeg" /></figure><p>Let’s say you’re building a data visualization using <a href="https://d3js.org/">D3</a> and <a href="https://en.wikipedia.org/wiki/Scalable_Vector_Graphics">SVG</a>. You may hit a ceiling when you try to display several thousand elements at the same time. Your browser may start to puff under the weight of all those <a href="https://css-tricks.com/dom/">DOM elements</a>.</p><p>Well here comes <a href="https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial">HTML5 Canvas</a> to the rescue! It’s much faster, so it can solve your browser’s puffing problems.</p><p>But you may quickly find yourself daunted. Because D3 and Canvas works a bit differently from D3 and SVG — especially when it comes to drawing and adding interactivity.</p><p>But fear not — it’s not that complicated. Any experience you’ve had with building visuals with D3 and SVG — or approaching D3 with a different renderer — will help you tremendously.</p><p>This tutorial built on the shoulders of giants who have already covered Canvas well. I learned these three tutorials by heart and I recommend you do, too:</p><ul><li><a href="https://bocoup.com/weblog/d3js-and-canvas">Working with D3.js and Canvas: When and How</a> from Irene Ros</li><li><a href="https://bocoup.com/weblog/2d-picking-in-canvas">Needles, Haystacks, and the Canvas API</a> from Yannick Assogba</li><li><a href="http://www.visualcinnamon.com/2015/11/learnings-from-a-d3-js-addict-on-starting-with-canvas.html">Learnings from a D3.js addict on starting with Canvas</a> from Nadieh Bremer</li></ul><p>So why continue reading this, then? Well, when I want to learn something new, it helps me a great deal to look at the same subject from slightly different angles. And this tutorial <em>is</em> a slightly different angle.</p><p>Also, this tutorial covers the three key steps: <strong>binding data</strong>, <strong>drawing elements</strong>, and <strong>adding interactivity </strong>— and it does all this in one go, with an added <strong>step-by-step manual</strong> to set you up.</p><h3>What do we build?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/0*HLs-n1NBIZoV1_vV.png" /><figcaption>A grid of pretty colours</figcaption></figure><p>A grid of (many) squares. Their colours aren’t of any deep meaning but don’t they look pretty? The important bit is that you can update it (to cover binding and updating data), that it has many elements (up to 10,000 in order for canvas to pay out), and that you can hover over each square to show square-specific information (interactivity). You can play with it <a href="http://bl.ocks.org/larsvers/raw/d187337850d58a444082841c739985ca/">here on a full screen</a> or <a href="http://blockbuilder.org/larsvers/d187337850d58a444082841c739985ca">here with all the code</a></p><h3>The mental model</h3><p>Before we actually dive in, let’s quickly step back and grasp conceptually what we do when we create elements with D3 to draw them to the screen. Skip this if you just want to make things.</p><p>The first step when using D3 usually doesn’t involve drawing — it involves preparing all your elements you want to draw. It’s a bit like building some LEGO. You can rip open the box and start building something or you can look at the manual first and build it according to the blueprint. The manual is your mental model, a blueprint or recipe of what you want to build.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*yo8Eqo53pAt1BaGcqam6vw.jpeg" /><figcaption>A mental model turned material (Mike, 2009 <a href="https://creativecommons.org/licenses/by/2.0/">https://creativecommons.org/licenses/by/2.0/</a>)</figcaption></figure><p>What is D3’s model? Apart from the large number of helpful functions and methods that calculate positions, re-shape datasets (the layouts) and generate functions that draw, for example, paths for us, D3 has a model for how the elements’ lives should evolve on the screen. It has a certain way to think about the lifecycle of each element.</p><p>Less ethereally, you inject data into a yet non-existent DOM, and D3 creates new elements of your choice as per the data you inject. Usually one element per datapoint. If you want to inject new data into the DOM you can do so and D3 identifies which elements have to be newly created, which elements are allowed to stay and which elements should pack up and leave the screen.</p><p>D3 is usually used in conjunction with SVG or sometimes with HTML-elements. In this orthodox case, you can see the data in the DOM when you choose to look at it through the console, for example. You can grab it, you can move it up or down the DOM and you can — importantly — add interactivity to each element you like to show, for example, a tooltip.</p><p>But — on the downside — you can’t show a lot of elements. Why? Because the more elements you push into the DOM, the harder the browser has to work to display them all. Let them also move around and the browser needs to re-calculate them constantly. The more knackered the browser gets the lower your frame rate or FPS (Frames Per Second), which measures how many frames the browser can paint each second. A frame rate of 60 is good and enables a fluid experience as long as no frames are missed — a frame rate of anything under 30 can equal a choppy ride. So when you want to show more elements, you can revert to canvas.</p><p>Why canvas? Canvas is an HTML5 element which comes with its own API to paint on it. All elements drawn on the canvas element won’t manifest in the DOM and save a lot of work for the browser. They are drawn in <a href="https://en.wikipedia.org/wiki/Immediate_mode_%28computer_graphics%29">immediate mode</a>. This means the rendered elements won’t get saved in the DOM but your instructions draw them directly to a particular frame. The DOM only knows the one canvas element; everything on it is only in memory. If you want to change your canvas elements you have to redraw the scene for the next frame.</p><p>The problem with this is of course that you can’t communicate directly with these non-material elements living in memory. You have to find a way to talk to them indirectly. This is where the D3 model comes in as well as custom or ‘virtual’ DOM-elements. What you’ll do in principal is:</p><ol><li>Bind your data to custom DOM elements. They don’t live in the DOM but only in memory (in a ‘virtual’ DOM) and describe the life-cycle of these elements in a known D3 way.</li><li>Use canvas to draw these elements.</li><li>Add interactivity with a technique called ‘picking’.</li></ol><p>Let’s do it.</p><h3>The data</h3><p>Before we start to code, let’s produce some data. Let’s say you want 5,000 datapoints. So let’s create an array with 5,000 elements, each of which is an object with just a single property value carrying the element’s index. Here’s how you create it with d3.range(). <a href="https://github.com/d3/d3-array/blob/master/README.md#range">d3.range()</a> is a D3 utility function, that creates an array based on its argument:</p><pre>var data = [];</pre><pre>d3.range(5000).forEach(function(el) {</pre><pre>  data.push({ value: el }); </pre><pre>});</pre><p>Here’s how the data looks in the console</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/0*OHi64vMvJF864r7M.png" /></figure><p>Thrills!</p><h3>The canvas container and its tools</h3><p>The canvas element is an HTML element. It’s conceptually very much like any SVG-parent-element, which I at least usually add to a simple container div as in:</p><pre>&lt;div id=“container”&gt;&lt;/div&gt;</pre><p>So, let’s add it to your container with D3 as in…</p><pre>var width = 750, height = 400;</pre><pre>var canvas = d3.select(&#39;#container&#39;)<br>  .append(&#39;canvas&#39;)<br>  .attr(&#39;width&#39;, width)<br>  .attr(&#39;height&#39;, height);</pre><pre>var context = canvas.node().getContext(&#39;2d&#39;);</pre><p>You also need to add the context, which is the canvas toolbox. The context variable is from now on the object carrying all the properties and methods, the brushes and colours you need to draw on the canvas. Without the context, the canvas element would remain empty and white. That’s all you need to setup — a canvas and its tools…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*nVD-z8kyZHvxkC-tgJtVrQ.png" /><figcaption>Base by Stilfehler — Own work, CC BY-SA 3.0, <a href="https://commons.wikimedia.org/w/index.php?curid=5899171">https://commons.wikimedia.org/w/index.php?curid=5899171</a>; blue Lego by David Lofink, 2008 <a href="https://creativecommons.org/licenses/by/2.0/">https://creativecommons.org/licenses/by/2.0/</a></figcaption></figure><h3>The HTML</h3><p>…is simple. The main HTML structure of your site will be:</p><pre>&lt;!-- A title --&gt;<br>&lt;h3&gt;Coloured grids&lt;/h3&gt;</pre><pre>&lt;!-- An input field with a default value. --&gt; <br>&lt;input type=&quot;text&quot; id=&quot;text-input&quot; value=&quot;5000&quot;&gt;</pre><pre>&lt;!-- An explanation... --&gt; <br>&lt;div id=&quot;text-explain&quot;&gt;...takes numbers between 1 and 10k&lt;/div&gt;</pre><pre>&lt;!-- ...and a container for the canvas element. --&gt; <br>&lt;div id=&quot;container&quot;&gt;&lt;/div&gt;</pre><h3>The Javascript structure</h3><p>On a top level you only need 2 functions:</p><pre>databind(data) {</pre><pre>  // Bind data to custom elements.</pre><pre>}</pre><pre>draw() {</pre><pre>  // Draw the elements on the canvas.</pre><pre>}</pre><p>Pretty straight forward so far.</p><h3>Bind the elements</h3><p>To bind data to the elements you first create a base element for all your custom elements you will produce and draw. If you know D3 well, think of it as a replacement to the SVG element:</p><pre>var customBase = document.createElement(&#39;custom&#39;);</pre><pre>var custom = d3.select(customBase); <br>// This is your SVG replacement and the parent of all other elements</pre><p>Then you add some settings for your grid. In short, these settings allow you to draw a grid of squares. 100 squares build a ‘parcel’ and there is a line break after 10 parcels (or after 1,000 squares). You can adjust this for different ‘parceling’ of the squares or different line-breaking. Or just not worry about it. I suggest the latter…</p><pre>// Settings for a grid with 10 cells in a row, <br>// 100 cells in a block and 1000 cells in a row.</pre><pre>var groupSpacing = 4; <br>var cellSpacing = 2; <br>var offsetTop = height / 5; <br>var cellSize = Math.floor((width - 11 * groupSpacing) / 100) - cellSpacing;</pre><p>Now let’s start the data-binding mission. Let’s get the necessities out of the way first and create a colour scale you will apply to your squares a little later.</p><pre>function databind(data) {</pre><pre>// Get a scale for the colours - not essential but nice.</pre><pre>colourScale = d3.scaleSequential(d3.interpolateSpectral)      <br>                .domain(d3.extent(data, function(d) { return d; }));</pre><p>Now let’s join your data to the ‘replacement-SVG’ you called custom above and add yet non-existing custom elements with the class .rect</p><pre>var join = custom.selectAll(&#39;custom.rect&#39;)<br>  .data(data);</pre><p>You enter the custom elements (remember nothing enters the DOM, this is all in memory).</p><pre>var enterSel = join.enter()<br>  .append(&#39;custom&#39;)<br>  .attr(&#39;class&#39;, &#39;rect&#39;)<br>  .attr(&quot;x&quot;, function(d, i) {<br>    var x0 = Math.floor(i / 100) % 10, x1 = Math.floor(i % 10);     <br>    return groupSpacing * x0 + (cellSpacing + cellSize) * (x1 + x0 * 10); })<br>  .attr(&quot;y&quot;, function(d, i) {<br>  var y0 = Math.floor(i / 1000), y1 = Math.floor(i % 100 / 10); <br>  return groupSpacing * y0 + (cellSpacing + cellSize) * (y1 + y0 * 10); })<br>  .attr(&#39;width&#39;, 0)<br>  .attr(&#39;height&#39;, 0);</pre><p>When an element enters your model, you just give it an x and a y position as well as a width and a height of 0, which you’ll change in the upcoming update selection…</p><p>You merge the enter selection into the update selection and define all attributes for the update and enter selection. This includes a width and a height value as well as a colour from the colour scale you built earlier:</p><pre>join <br>  .merge(enterSel)<br>  .transition()<br>  .attr(&#39;width&#39;, cellSize)<br>  .attr(&#39;height&#39;, cellSize)<br>  .attr(&#39;fillStyle&#39;, function(d) { return colourScale(d); });</pre><p>Two things of note about this last line. When you work with SVG this line would be</p><pre>.style(&#39;color&#39;, function(d) { return colourScale(d); })</pre><p>But with canvas you use .attr(). Why? Your main interest here is to find a pain-free way to transfer some element-specific information. Here you want to transfer a colour-string from the databind() to the draw() function. You use the element simply as a vessel to transport your data over to where it is being rendered to the canvas.</p><p>That&#39;s a very important distinction: when working with SVG or HTML you can bind data to elements and draw or apply styles to the elements in one step. In canvas you need two steps. First you bind the data then you draw the data. You can&#39;t style the elements while binding. They only exist in memory and canvas can&#39;t be styled via CSS style properties, which is exactly what you access when using .style().</p><p>At first, this might seem limiting as you can do less in one step, but it’s conceptually almost cleaner and also gives you some freedom. .attr() allows us to send any key-value pairs on the journey. You could use other methods like the HTML .dataset property for example, but .attr() will do just fine.</p><p>Notice we don&#39;t say color but fillStyle. To be honest, you could use color or you could use chooChooTrain here. You would only need to remember this when you fetch the information later during drawing. However, as canvas uses a property called fillStyle to style elements, it seems more appropriate in this case.</p><p>Finally, you also define the exit selection, deciding what should happen to exiting elements.</p><pre>var exitSel = join.exit()<br>  .transition()<br>  .attr(&#39;width&#39;, 0)<br>  .attr(&#39;height&#39;, 0)<br>  .remove();</pre><p>That’s it! You can close your databind() function and move on...</p><pre>} // databind()</pre><p>This is not really scary coming from D3 as it’s pretty much exactly the same. You have now successfully created your data model, the way the application will think about data. Each element will get the properties it needs to be drawn via the .attr() functions and each element will be assigned a life-cycle state depending on the injected data. Our standard D3 model.</p><h3>Drawing the elements</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mjyE-tKqxgB7siqnoDxMsQ.jpeg" /><figcaption>By Kristina Alexanderson, 2011 <a href="https://creativecommons.org/licenses/by-nc-nd/2.0/">https://creativecommons.org/licenses/by-nc-nd/2.0/</a></figcaption></figure><p>Now you need to write the draw function to get the elements on screen. Let’s just note here that nothing has happened yet. You haven’t called databind() yet because you need to find a way to draw it to the canvas first. So here we go... The draw() function doesn&#39;t need to take any arguments in this case:</p><pre>function draw() {</pre><p>As mentioned fleetingly above, you need to take care of cleaning the canvas every time you draw afresh. The DOM is material, in that when you draw a rect-element on it and you change its x value, it will move in the x-direction and the DOM will take care of this move (or the re-paint) automatically.</p><p>If you move a rect from x = 0 to x = 1 at a certain point in time (after a button press for example) the browser will move the rect from 0 to 1 within one tick or frame-paint (which is roughly 16ms long). If you move it from 0 to 10, it will do so in a time depending on the duration you asked this transition to happen, maybe 1 pixel per tick maybe 8 pixel per tick (for more read <a href="https://www.html5rocks.com/en/tutorials/speed/unnecessary-paints/">this</a> blog post).</p><p>But it will tell the pixel at 0 that the rect has disappeared and the pixel at 1 that there is a rect now. Canvas doesn’t do this. You need to tell canvas what to paint, and if you paint something new, you need to tell it to remove the previous paint.</p><p>So let’s start with cleaning up anything that might be on the canvas before you draw. Here’s how:</p><pre>context.clearRect(0, 0, width, height); // Clear the canvas.</pre><p>Simple.</p><p>Now you…</p><ol><li>…get hold of all elements in order to</li><li>loop through all elements and</li><li>take the information you have stored in the databind() function to draw the element:</li></ol><pre>// Draw each individual custom element with their properties.</pre><pre>var elements = custom.selectAll(&#39;custom.rect&#39;);<br>// Grab all elements you bound data to in the databind() function.</pre><pre>elements.each(function(d,i) { // For each virtual/custom element...</pre><pre>  var node = d3.select(this); <br>  // This is each individual element in the loop. <br>  <br>  context.fillStyle = node.attr(&#39;fillStyle&#39;); <br>  // Here you retrieve the colour from the individual in-memory node and set the fillStyle for the canvas paint</pre><pre>  context.fillRect(node.attr(&#39;x&#39;), node.attr(&#39;y&#39;), node.attr(&#39;width&#39;), node.attr(&#39;height&#39;));<br>  // Here you retrieve the position of the node and apply it to the fillRect context function which will fill and paint the square.</pre><pre>}); // Loop through each element.</pre><p>And that’s it! You can close the draw() function</p><pre>} // draw()</pre><p>When I started with canvas after a while of wanting to dive into it, this simplicity really upped my spirits.</p><p>However, nothing has happened in the browser yet. We have the tools in the databind() and the draw() function, but nothing has been drawn yet. How do you do this? If you just wanted to draw a static visual or image, you just call:</p><pre>databind(data);</pre><pre>draw();</pre><p>This would bind the data to the custom elements, which would live in memory and then draw it — once!</p><p>But you have transitions. Remember above: when you wrote the databind() function you transitioned the cell width and height from 0 to their size as well as the colour from black (the default) to the respective element’s colour. A default D3 transition lasts 250 milliseconds, so you need to redraw the squares many times in these 250 ms in order to get a smooth transition. How do you do this?</p><p>It’s again simple. You just call databind(data) to create our custom elements before you repeatedly call draw() for as long as it takes the transition to run. So in our case at least 250 ms. You could use setInterval() for this but we really should use requestAnimationFrame() in order to be as performant as possible (for more <a href="https://css-tricks.com/using-requestanimationframe/">read this</a>). There are a few ways to use it, but keeping within the D3 spirit, I suggest using d3.timer() which implements requestAnimationFrame() as well as being straight forward to use. So here we go:</p><pre>// === First call === //</pre><pre>databind(d3.range(value)); // Build the custom elements in memory.</pre><pre>var t = d3.timer(function(elapsed) {</pre><pre>  draw();</pre><pre>  if (elapsed &gt; 300) t.stop();</pre><pre>}); // Timer running the draw function repeatedly for 300 ms.</pre><p>d3.timer() calls the callback repeatedly until elapsed (which is the passed time in milliseconds from instantiation) is past 300 and then the timer is stopped. In these 300 milliseconds, it runs the draw() at each tick (roughly each 16ms). draw() then looks at each element&#39;s attributes and draws them accordingly.</p><p>This is how a transition works in canvas. You call the drawing function right after the binding function many times. Whatever your D3-model is set up to transition (positions, colours, sizes) will be re-drawn many times with small incremental changes for each draw</p><p>Note that draw() needs to come right after the databind() function. You couldn&#39;t ask the machine to run databind(), then do something else for a second and then call draw(). Because after 1 second the transitioned states calculated by your databind() function have all transitioned already. Done, dusted and forgotten.</p><p>That’s it! You’ve bound data to custom elements and you’ve drawn it to the canvas.</p><h4>Let the user update the number of squares</h4><p>To give the user the chance to repeat this feat with a custom number of elements (ok, semi-custom with a maximum of 10,000) you add the following listener and handler to your text-input box:</p><pre>// === Listeners/handlers === //</pre><pre>d3.select(&#39;#text-input&#39;).on(&#39;keydown&#39;, function() {</pre><pre>if (d3.event.keyCode === 13) { <br>// Only do something if the user hits return (keycode 13).</pre><pre>  if (+this.value &lt; 1 || +this.value &gt; 10000) { <br>  // If the user goes lower than 1 or higher than 10k...<br>     <br>    d3.select(&#39;#text-explain&#39;).classed(&#39;alert&#39;, true); <br>    // ... highlight the note about the range and return.</pre><pre>    return;</pre><pre>  } else { <br>  // If the user types in a sensible number...</pre><pre>    d3.select(&#39;#text-explain&#39;).classed(&#39;alert&#39;, false); <br>    // ...remove potential alert colours from the note...</pre><pre>    value = +this.value; // ...set the value...</pre><pre>    databind(d3.range(value)); // ...and bind the data.</pre><pre>    var t = d3.timer(function(elapsed) {</pre><pre>      draw();<br>  <br>      if (elapsed &gt; 300) t.stop();</pre><pre>    }); // Timer running the draw function repeatedly for 300 ms. <br>  <br>  } // If user hits return.</pre><pre>}); // Text input listener/handler</pre><p>Here it is again, our colourful grid of canvas squares, ready to be updated and redrawn:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/0*qn1l_CMYhpDR9_fW.png" /></figure><h3>Interactivity</h3><p>The biggest ‘pain’ with canvas in comparison to SVG or HTML is that there are no material elements living in the DOM. If there were you could just register listeners to the elements and add handlers to the listeners. For example you can trigger a mouse-over on an SVG rect element and whenever the listener triggers, you could do something to the rect. Like showing data values stored with the rect in a tooltip.</p><p>With canvas you have to find another way to make an event heard on our canvas elements. Luckily there are a number of clever people who thought of an indirect but logical way.</p><p>So what interactivity do we want? As said above let’s go for a tooltip and let’s assume you want to show the index of the square in a tooltip as soon as you hover over the element. Not very thrilling, but the key is that you can access the data bound to the element by hovering over it.</p><h4>Picking</h4><p>There are a few steps involved (all logical though). But in short you will build two canvases to achieve this. One <strong>main canvas</strong> that produces our visual and one <strong>hidden canvas</strong> (as in we can’t see it) that produces the same visual. The key here is that all elements on the second canvas will be at the exact same position in relation to the canvas origin compared to the first canvas. So square 1 starts on 0,0 on the main canvas as well as on the hidden canvas. Square 2 starts on 8,0 on the main canvas as well as on the hidden canvas and so on.</p><p>There is only one important difference. Each element on the hidden canvas will get a unique colour. We will create an object (or rather an <a href="https://en.wikipedia.org/wiki/Associative_array">associative array</a> or <em>map</em> for brevity) that links each unique colour to each element’s data.</p><p>Why? Because next we attach a mouse-move listener to the main-canvas to retrieve a stream of mouse-positions. At each mouse-position we can use a canvas-own method to “pick” the colour at this exact position. Then we just look up the colour in our associative array and we have the data ! And we’re flying…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*SzAIRO3WI8GRXTbyWs7uSg.jpeg" /><figcaption>By Kenny Louie, 2010 <a href="https://creativecommons.org/licenses/by/2.0/">https://creativecommons.org/licenses/by/2.0/</a></figcaption></figure><p>You could say “well, my squares have already got a unique colour, I can use those?” And indeed, you could use them. However, your interactivity would go out of the window as soon as you decide to bereft your squares from the colours. So you should make sure to always have one canvas — the hidden canvas — that has a guaranteed set of unique colours for the squares.</p><p>Let’s apply this technique step by step. The code you’ve built so far can stay as it is — you just add to it as you go along.</p><h4>1. Prepare the hidden canvas</h4><p>First let’s create the hidden canvas that will harbour our visual with a unique colour per square.</p><p>1.1 Create hidden canvas element and set its CSS to { display: none; }.</p><pre>// Rename the main canvas and add a &#39;mainCanvas&#39; class to it.</pre><pre>var mainCanvas = d3.select(&#39;#container&#39;)<br>  .append(&#39;canvas&#39;)<br>  .classed(&#39;mainCanvas&#39;, true)<br>  .attr(&#39;width&#39;, width) .attr(&#39;height&#39;, height);<br> <br>// new ----------------------------------- </pre><pre>// Add the hidden canvas and give it the &#39;hiddenCanvas&#39; class.</pre><pre>var hiddenCanvas = d3.select(&#39;#container&#39;)<br>  .append(&#39;canvas&#39;)<br>  .classed(&#39;hiddenCanvas&#39;, true) <br>  .attr(&#39;width&#39;, width) <br>  .attr(&#39;height&#39;, height);</pre><p>In fact, I won’t set the canvas to hidden in this example to show what is going on. But to do so, just add .hiddenCanvas { display: none; } to your CSS and the deed is done.</p><p>1.2 Build the context variable in the draw() function and pass two arguments to the function: the canvas as well as a boolean called &#39;hidden&#39; determining which canvas we build (hidden = true || false) as in:</p><pre>function draw(canvas, hidden) {</pre><p>1.3 You now need to adapt all draw functions to include the two new draw() arguments. So from now on, you don&#39;t just call draw() you call either draw(mainCanvas, false) or draw(hiddenCanvas, true)</p><h4>2. Apply unique colours to the hidden elements and map them</h4><p>Here, dear reader, comes the key part of our operation, the engine of our truck, the spice in our soup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4KLe0pmeZqWz3I-DsSw5lA.jpeg" /><figcaption>By Andrew Becraft, 2007 <a href="https://creativecommons.org/licenses/by-nc-sa/2.0/">https://creativecommons.org/licenses/by-nc-sa/2.0/</a></figcaption></figure><p>2.1 Include a function to generate a new unique colour every time it gets called (via <a href="http://stackoverflow.com/a/15804183">Stack Overflow</a>)</p><pre>// Function to create new colours for the picking.</pre><pre>var nextCol = 1;</pre><pre>function genColor(){ <br>  <br>  var ret = [];</pre><pre>  if(nextCol &lt; 16777215){ <br>    <br>    ret.push(nextCol &amp; 0xff); // R <br>    ret.push((nextCol &amp; 0xff00) &gt;&gt; 8); // G <br>    ret.push((nextCol &amp; 0xff0000) &gt;&gt; 16); // B</pre><pre>    nextCol += 1; <br>  <br>  }</pre><pre>var col = &quot;rgb(&quot; + ret.join(&#39;,&#39;) + &quot;)&quot;;</pre><pre>return col;</pre><pre>}</pre><p>genColour() produces a colour defining string in the form rgb(0,0,0). Every time it&#39;s called it increments the R value by one. Once it reaches 255, it increments the G value by 1 and resets the R value to 0. Once it reaches r(255,255,0) it increments the B value by 1 resetting the R and the G to 0 and so on.</p><p>So in total you can have 256*256*256 = 16.777.216 elements to retain a unique colour. However, I can assure you your browser will die beforehand. Even with canvas (webGL tutorial to follow).</p><p>2.2 Create the map-object that will keep track of which custom element has which unique colour:</p><pre>var colourToNode = {}; // Map to track the colour of nodes.</pre><p>You can add the genColour() function wherever you want in your script, as long as it&#39;s outside the databind() and draw() function scope. But note that your map variable needs to be created before and beyond the scope of the databind() function.</p><p>2.3 Add a a unique colour to each custom element as for example .attr(&#39;fillStyleHidden&#39;) and <br>2.4 build the map-object during element creation</p><p>Here you’ll use your ‘colour-canon’ genColour() in our databind() function when assigning the fillStyle to our elements. As you also have access to each datapoint while it&#39;s being bound to each element, you can bring colour and data together in your colourToNode map.</p><pre>join <br>  .merge(enterSel) <br>  .transition() <br>  .attr(&#39;width&#39;, cellSize) <br>  .attr(&#39;height&#39;, cellSize) <br>  .attr(&#39;fillStyle&#39;, function(d) { <br>    return colorScale(d.value); <br>  });</pre><pre>  // new -----------------------------------------------------     <br>  <br>  .attr(&#39;fillStyleHidden&#39;, function(d) { </pre><pre>    if (!d.hiddenCol) {</pre><pre>      d.hiddenCol = genColor(); <br>      colourToNode[d.hiddenCol] = d;</pre><pre>    }</pre><pre>    // Here you (1) add a unique colour as property to each element <br>    // and(2) map the colour to the node in the colourToNode-map.</pre><pre>    return d.hiddenCol;</pre><pre>});</pre><p>2.5 You can now colour the elements according to the canvas the draw() function is rendering. You add a conditional on the fillStyle in the draw() function applying the colours for our visual to the main canvas and the unique colours to the hidden canvas. It&#39;s a simple one-liner:</p><pre>context.fillStyle = hidden ? node.attr(&#39;fillStyleHidden&#39;) : node.attr(&#39;fillStyle&#39;);</pre><pre>// The node colour depends on the canvas you draw.</pre><p>The main canvas still looks the same of course:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/0*jW24go1QVLh5RcQw.png" /></figure><p>Let’s finally add some interactivity and start with drawing the hidden canvas whenever we move the mouse onto our main canvas.</p><h4>3. Pick up the colours with the mouse</h4><p>3.1 First, simply register a listener to the main canvas, listening to mouse-move events.</p><pre>d3.select(&#39;.mainCanvas&#39;).on(&#39;mousemove&#39;, function() {</pre><pre>});</pre><p>Why mousemove? As you can’t register listeners with individual squares but have to use the entire canvas you won’t be able to work with mouseover or -out events as they will only trigger when entering the canvas not the elements. In order to get the mouse position on your canvas you can do mousemove or click/mousedown.</p><pre>d3.select(&#39;.mainCanvas&#39;).on(&#39;mousemove&#39;, function() {</pre><pre>  draw(hiddenCanvas, true); // Draw the hidden canvas.</pre><pre>});</pre><p>This way, the first thing our user triggers when mousing over the main canvas is to unknowingly create the hidden canvas. As said, in production this canvas would be hidden, but for our educational purposes we want to see it and indeed, trigger the hidden canvas to be drawn when the mouse moves over the main canvas like so:</p><p>The colours on the main canvas range from black to red, from rgb(0,0,0) to rgb(255,0,0) and then it looks as if the same range from black to red is repeated. However, now the colour ranges from a slightly greener black, precisely from rgb(0,1,0) to rgb(255,1,0):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/0*uEF_LwzGb-h6OgUr.png" /></figure><p>Zooming into the first couple of hundred squares, here are the colours of the first, the 256th and the 257th square:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*g8-fUn6bZhZqgFmM.png" /></figure><p>3.3 As our hidden canvas is structurally a carbon copy of our main canvas, all the hidden canvas elements will be at the same position as the elements on our main canvas. So, you can now use the mouse’s x and y positions you are collecting from the listener on the main canvas to establish the same location on the hidden canvas. Back in the listener, you add:</p><pre>d3.select(&#39;.mainCanvas&#39;).on(&#39;mousemove&#39;, function() {   <br>  <br>  // Draw the hidden canvas.<br>  draw(hiddenCanvas, true);</pre><pre>  // Get mouse positions from the main canvas.<br>  var mouseX = d3.event.layerX || d3.event.offsetX; <br>  var mouseY = d3.event.layerY || d3.event.offsetY; });</pre><p>Note here we take the event.layerX and event.layerY properties which return the mouse position including scrolling. <a href="https://developer.mozilla.org/en/docs/Youb/API/UIEvent/layerX">This can break</a> so use offsetX as a fallback (or just use offsetX).</p><p>3.4 The picking: Canvas greatly allows access to the pixel-data the mouse is hovering over with the getImageData() function and its .data property. In full bloom this will look like:</p><p>getImageData(posX, posY, 1, 1).data .</p><p>It will return an array with four numbers: the R, the G, the B and the alpha value. As you diligently built the colourToNode map assigning the element data to each of its hidden colours, you can now access this element&#39;s data simply by looking up the colour in the map!</p><pre>d3.select(&#39;.mainCanvas&#39;).on(&#39;mousemove&#39;, function() {</pre><pre>  // Draw the hidden canvas.<br>  draw(hiddenCanvas, true);</pre><pre>  // Get mouse positions from the main canvas.<br>  var mouseX = d3.event.layerX || d3.event.offsetX; <br>  var mouseY = d3.event.layerY || d3.event.offsetY;</pre><pre>// new -----------------------------------------------</pre><pre>  // Get the toolbox for the hidden canvas.<br>  var hiddenCtx = hiddenCanvas.node().getContext(&#39;2d&#39;);</pre><pre>  // Pick the colour from the mouse position. <br>  var col = hiddenCtx.getImageData(mouseX, mouseY, 1, 1).data; </pre><pre>  // Then stringify the values in a way our map-object can read it.<br>  var colKey = &#39;rgb(&#39; + col[0] + &#39;,&#39; + col[1] + &#39;,&#39; + col[2] + &#39;)&#39;;</pre><pre>  // Get the data from our map! <br>  var nodeData = colourToNode[colKey];</pre><pre>  console.log(nodeData);</pre><pre>});</pre><p>And indeed, logging the nodeData to the console returns an object every time you hover over a square:</p><p>The data per node now shows the value which constitutes the original data as well as the key hiddenCol showing this node&#39;s colour for the hidden canvas:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/0*wPFn_0asON7IAoRH.png" /></figure><p>3.5 Finally — and that’s a formality — you add the tooltip</p><pre>d3.select(&#39;.mainCanvas&#39;).on(&#39;mousemove&#39;, function() {</pre><pre>  // Draw the hidden canvas.<br>  draw(hiddenCanvas, true);</pre><pre>  // Get mouse positions from the main canvas.<br>  var mouseX = d3.event.layerX || d3.event.offsetX; <br>  var mouseY = d3.event.layerY || d3.event.offsetY;</pre><pre>  // Get the toolbox for the hidden canvas.<br>  var hiddenCtx = hiddenCanvas.node().getContext(&#39;2d&#39;);</pre><pre>  // Pick the colour from the mouse position. <br>  var col = hiddenCtx.getImageData(mouseX, mouseY, 1, 1).data;</pre><pre>  // Then stringify the values in a way our map-object can read it.<br>  var colKey = &#39;rgb(&#39; + col[0] + &#39;,&#39; + col[1] + &#39;,&#39; + col[2] + &#39;)&#39;;</pre><pre>  // Get the data from our map! <br>  var nodeData = colourToNode[colKey]; <br>  <br>  console.log(nodeData);</pre><pre>  // new -----------------------------------------------</pre><pre>  if (nodeData) { <br>  // Show the tooltip only when there is nodeData found by the mouse</pre><pre>    d3.select(&#39;#tooltip&#39;) <br>      .style(&#39;opacity&#39;, 0.8) <br>      .style(&#39;top&#39;, d3.event.pageY + 5 + &#39;px&#39;) <br>      .style(&#39;left&#39;, d3.event.pageX + 5 + &#39;px&#39;)   <br>      .html(nodeData.value); </pre><pre>  } else { <br>  // Hide the tooltip when the mouse doesn&#39;t find nodeData.<br>  <br>    d3.select(&#39;#tooltip&#39;).style(&#39;opacity&#39;, 0); <br>  <br>  }</pre><pre>}); // canvas listener/handler</pre><p>That’s it! You’ve visualised a large number of elements on canvas — more than you would’ve been able to enjoy problem-free with SVG. You still used D3’s lifecycle model and you added some interactivity to access the data attached to each element. These three steps should enable you to do pretty much anything or at least more than what you’re used to when working with D3 and SVG.</p><p>There’s a <a href="http://www.datamake.io/blog/d3-canvas-full#manual">step-by-step manual</a> from scratch to interactive D3/canvas on my blog which allows internal page links. This way you can see the whole process in one view and click your way through it with ease:</p><figure><a href="http://www.datamake.io/blog/d3-canvas-full#manual"><img alt="" src="https://cdn-images-1.medium.com/max/500/1*1PHIYkg6u2RKW3NN4wCzVA.png" /></a><figcaption>Click to get to the manual</figcaption></figure><p>…and <a href="http://blockbuilder.org/larsvers/6049de0bcfa50f95d3dcbf1e3e44ad48">here’s the full code again</a>.</p><p>I hope you enjoyed reading this and please do say <a href="http://www.datamake.io/contact">hello</a> and/or …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*Ca-yaR3xX9gbEETkmfF1dg.png" /></figure><p><em>lars verspohl </em><a href="http://www.datamake.io/"><em>www.datamake.io</em></a><em> @lars_vers </em><a href="https://www.linkedin.com/in/larsverspohl"><em>https://www.linkedin.com/in/larsverspohl</em></a></p><p><em>…is always grateful for a like💚 or a follow he can return.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8505c8b27444" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/d3-and-canvas-in-3-steps-8505c8b27444">D3 and Canvas in 3 steps</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to turn D3 and Canvas into good friends]]></title>
            <link>https://medium.com/@lverspohl/how-to-turn-d3-and-canvas-into-good-friends-b7a240a32915?source=rss-3ed15968ada5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7a240a32915</guid>
            <category><![CDATA[design]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[3d]]></category>
            <dc:creator><![CDATA[lars verspohl]]></dc:creator>
            <pubDate>Fri, 09 Dec 2016 16:01:02 GMT</pubDate>
            <atom:updated>2018-01-17T08:07:37.182Z</atom:updated>
            <content:encoded><![CDATA[<h3>D3 and Canvas Part 1</h3><h4>Part 1 Binding and Drawing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*JHIOXs1E5SX-LalsIDNjQQ.png" /></figure><h3>Introduction</h3><p>When building visualisations with D3 and SVG you might hit a ceiling after a couple of thousand elements as the browser will start puffing under the weight of adding so many elements to the DOM. The big benefit of HTML5 Canvas is that it’s much more performant and hence can solve your puffing problems. However, approaching canvas from the save D3/SVG haven might be daunting as working with it is slightly different — especially drawing and adding interactivity. But, fear not, it’s actually simple and having build visuals with D3/SVG, approaching D3 with a different renderer (a different technology drawing elements to the screen) will help your conceptual understanding of D3 and the related web technologies significantly.</p><p>Now this tutorial is standing on giant shoulders who’s owners have covered the ground in parts or in full already. There is a total of 3 I learned by heart and they are excellent as they are:</p><ul><li><a href="https://bocoup.com/weblog/d3js-and-canvas">Working with D3.js and Canvas: When and How</a> from Irene Ros</li><li><a href="https://bocoup.com/weblog/2d-picking-in-canvas">Needles, Haystacks, and the Canvas API</a> from Yannick Assogba</li><li><a href="http://www.visualcinnamon.com/2015/11/learnings-from-a-d3-js-addict-on-starting-with-canvas.html">Learnings from a D3.js addict on starting with Canvas</a> from Nadieh Bremer</li></ul><p>Why continue reading? When learning something new it helps me a great deal to look at the same subject from slightly different angles. This is a slightly different angle. Also unlike the first 2 above it covers all of the three fundamental steps in building visualisation: binding, drawing and interactivity and unlike Nadieh’s post it adds a great deal of detail ultimately in the shape of a detailed manual for the interactivity part — potentially the most complex of the steps when working with canvas.</p><h3>What do we build?</h3><p>This:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/0*bXJZMJxbiVvEBkpV.png" /></figure><p>A grid of (many) squares. Their colours aren’t of any deep meaning but don’t they look pretty? What is important indeed is that we can update it (focusing on how to bind and update data), that it has many elements (up to 10k so that canvas pays out), and that we can hover over each square and square-specific information will be shown (interactivity). You can play with it <a href="http://bl.ocks.org/larsvers/raw/d187337850d58a444082841c739985ca/">here on a full screen</a> or <a href="http://blockbuilder.org/larsvers/d187337850d58a444082841c739985ca">here with all the code</a>.</p><h3>The mental model</h3><p>Before we actually dive in, let’s quickly step back and conceptually grasp what we’ll do when creating elements with D3 and drawing them to the screen. Skip this if you just want to make things….</p><p>The first step when using D3 usually doesn’t involve drawing — it involves preparing all our elements we want to draw. It’s a bit like building some LEGO. We can rip open the box and start building something or we look at the manual first and build it according to this blueprint. The manual is our mental model, a blueprint or recipe of what we want to build.</p><p>What is D3’s model? Apart from the large number of enormously helpful functions and methods that calculate positions, re-shape datasets (the layouts) and generate functions that draw for example paths for us, D3 has a model for how the elements’ lives should evolve on the screen. It has a certain way to think about the lifecycle of each element. Less ethereally, we inject data into a yet non-existent DOM, D3 then creates new elements of our choice as per the data we inject — usually one element per datapoint. If we wanted to inject new data into the DOM we can do so and D3 identifies which elements have to be newly created, which elements are allowed to stay and which elements should pack in and leave the screen.</p><p>We usually use D3 in conjunction with SVG or sometimes with HTML-elements. In this orthodox case, we can see the data in the DOM when we choose to look at it through the console for example. We can grab it, we can move it up or down the DOM and we can — importantly — add interactivity to each element we like to show for example a tooltip. But — on the downside — we can’t show a lot of elements. Why? Because the more elements we push into the DOM, the harder our browser has to work to display them all. Let them also move around and the browser needs to re-calculate them constantly. The more knackered our browser gets the lower our frame rate or FPS (Frames Per Second), which is a measure describing how many frames the browser can paint each second. A frame rate of 60 is good and enables a fluid experience — a frame rate of anything under 25 equals a choppy ride. So when we want to show more elements, we can revert to canvas.</p><p>Why canvas? Canvas is an HTML5 element which comes with its own API to paint on it. All elements drawn on the canvas element won’t manifest in the DOM and save a lot of work for the browser. They are drawn in <a href="https://en.wikipedia.org/wiki/Immediate_mode_(computer_graphics)">immediate mode</a>, meaning the rendered elements won’t get saved in something like the DOM but our instructions draw them directly to a particular frame. The DOM only knows the one canvas element, everything on it is only in memory. If we want to change them we have to redraw the scene for the next frame.</p><p>The problem with this is of course that we can’t communicate directly with these non-material elements living in memory but have to find a way to talk to them indirectly. This is where our D3 model comes in as well as custom or ‘virtual’ DOM-elements. What we’ll do in principal is:</p><ol><li>Bind our data to custom DOM elements that don’t live in the DOM but only in memory (in our ‘virtual’ DOM) and describe the life-cycle of these elements in a known D3 way</li><li>Use canvas to draw these elements</li><li>Add interactivity with a technique called ‘picking’</li></ol><p>Let’s do it.</p><h3>The data</h3><p>Before we start to code, let’s produce some data. Let’s say we want 5000 datapoints, we just create an array with 5000 elements, each of which is an object with just a single property value carrying the element’s index. Here’s how we create it with d3.range(). d3.range() is a function built into D3, that <a href="https://github.com/d3/d3-array/blob/master/README.md#range">creates an array based on its argument</a>:</p><pre>var data = []; </pre><pre>d3.range(5000).forEach(function(el) { data.push({ value: el; }); });</pre><p>Here’s how our data looks in the console</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/0*fqgyG5ZKtSS1jUFA.png" /></figure><p>The thrills !</p><h3>The canvas container and it’s tools</h3><p>The canvas element is an HTML element. It’s conceptually very much like any svg-parent-element, which I at least usually add to a simple container div as in:</p><pre>&lt;div id=“container”&gt;&lt;/div&gt;</pre><p>So, let’s add it to our container with D3 as in…</p><pre>var width = 750, height = 400; </pre><pre>var canvas = d3.select(&#39;#container&#39;) <br>  .append(&#39;canvas&#39;) <br>  .attr(&#39;width&#39;, width) <br>  .attr(&#39;height&#39;, height); </pre><pre>var context = canvas.node().getContext(&#39;2d&#39;)</pre><p>We also added the context, which is the canvas toolbox. The context variable is from now on the object carrying all the properties and methods, the brushes and colours we need to draw on the canvas. Without the context, the canvas element would remain empty and white. That’s all we need to setup — a canvas and it’s tools…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*YqfgW3gNB4fU6MZs.png" /></figure><h3>The HTML</h3><p>…is simple. The main HTML structure of our site will be:</p><pre>&lt;!-- A title --&gt; <br>&lt;h3&gt;Coloured grids&lt;/h3&gt; </pre><pre>&lt;!-- An input field with a default value --&gt; <br>&lt;input type=&quot;text&quot; id=&quot;textinput&quot; value=&quot;5000&quot;&gt; </pre><pre>&lt;!-- An explanation --&gt; <br>&lt;div id=&quot;text-explain&quot;&gt;...takes numbers between 1 and 10k&lt;/div&gt; </pre><pre>&lt;!-- And a container for our canvas element --&gt; <br>&lt;div id=&quot;container&quot;&gt;&lt;/div&gt;</pre><h3>The Javascript structure</h3><p>On a top level we only need 2 functions:</p><pre>databind(data) { </pre><pre>  // bind data to custom elements </pre><pre>} </pre><pre>draw() { </pre><pre>  // draw the elements on the canvas </pre><pre>}</pre><h3>Bind the elements</h3><p>To bind the elements we first create a base element for all our custom elements we will produce and draw. If you know D3 well, think of it as a replacement to our svg element:</p><pre>var customBase = document.createElement(&#39;custom&#39;); </pre><pre>var custom = d3.select(customBase); // this is our svg replacement</pre><p>Then we add some settings for our grid. In short these settings allow us to draw a grid of squares which are packed together in square collections or ‘parcels’ of 100 and a line break after 10 parcels (so after 1000 squares). You can adjust this for different ‘parceling’ of the squares or different line-breaking, or just not worry about it. I suggest the latter…</p><pre>// settings for a grid with 10 cells in a row, <br>// 100 cells in a block and 1000 cells in a row </pre><pre>var groupSpacing = 4,<br>    cellSpacing = 2<br>    cellSize = Math.floor((width-11*groupSpacing)/100)-cellSpacing;</pre><p>Now let’s start our data-binding mission. Let’s get the necessities out of the way first and create a colour scale we will apply to our squares a little later.</p><pre>function databind(data) { </pre><pre>  // get a scale for the colours - not essential but nice </pre><pre>colourScale = d3.scaleSequential(d3.interpolateSpectral)<br>  .domain(d3.extent(data, function(d) { return d; }));</pre><p>Now let’s join our data to the ‘replacement-svg’ we called custom above and add yet non-existing custom elements with the class .rect</p><pre>var join = custom.selectAll(&#39;custom.rect&#39;) <br>  .data(data);</pre><p>We enter the custom elements (remember nothing enters the DOM, this is all in memory)</p><pre>var enterSel = join.enter()<br>  .append(&#39;custom&#39;)<br>  .attr(&#39;class&#39;, &#39;rect&#39;) <br>  .attr(&quot;x&quot;, function(d, i) { <br>    var x0 = Math.floor(i / 100) % 10, x1 = Math.floor(i % 10);<br>    return groupSpacing * x0 + (cellSpacing + cellSize) * (x1 + x0 * 10); }) <br>  .attr(&quot;y&quot;, function(d, i) { <br>    var y0 = Math.floor(i / 1000), y1 = Math.floor(i % 100 / 10);<br>    return groupSpacing * y0 + (cellSpacing + cellSize) * (y1 + y0 * 10); }) <br>   .attr(&#39;width&#39;, 0) <br>   .attr(&#39;height&#39;, 0);</pre><p>When an element enters our model, we just give it an x and a y position as well as a width and a height of 0, which we’ll change in the upcoming update selection…</p><p>We merge the enter selection into our update selection and define all attributes for the update and enter selection including a width and a height value and a colour from our colour scale we built earlier:</p><pre>join <br>  .merge(enterSel) <br>  .transition()<br>  .attr(&#39;width&#39;, cellSize)<br>  .attr(&#39;height&#39;, cellSize)<br>  .attr(&#39;fillStyle&#39;, function(d) { return colourScale(d); });</pre><p>2 things of note about this last line. When we work with SVG this line would be:</p><pre>.style(&#39;color&#39;, function(d) { return colourScale(d); })</pre><p>But with canvas we use .attr(). Why? Our main interest here is to find a pain-free way to transter some element-specific information - here: colour - from the databind() to the draw() function. We use the element simply as a vessel to transport our data over to where it is being rendered to the canvas. That&#39;s a very important distinction: when working with SVG or HTML we can bind data to elements and draw or apply styles to the elements in one step. In canvas we need two steps. First we bind the data then we draw the data. We can&#39;t style the elements while binding. Why? They only exist in memory and canvas can&#39;t be styled via CSS style properties, which is exactly what you access when using .style().</p><p>At first, this might seem limiting as we can do less in a single step, but it’s conceptually almost cleaner and gives us also some freedom we need. .attr() allows us to send any key-value pairs on the journey. We could use other methods like the HTML .dataset property for example, but .attr() will do just fine. You notice we don&#39;t say color but fillStyle. To be honest, we could use color or we could use chooChooTrain here — we would only need to remember this when we fetch the information later for the drawing. However, as canvas uses fillStyle to style elements, it seems more appropriate in this case. You might think differently...</p><p>Eventually we also define the exit selection, deciding what should happen to exiting elements.</p><pre>var exitSel = join.exit()<br>  .transition()<br>  .attr(&#39;width&#39;, 0)<br>  .attr(&#39;height&#39;, 0)<br>  .remove();</pre><p>That’s it ! We can close our databind() function and move on...</p><pre>} // databind()</pre><p>This is not really scary coming from D3 as it’s pretty much exactly the same. We have now successfully created our data model, the way the application will think about our data and our elements. Each element will get the properties it needs to be drawn via the .attr() functions and each element will be assigned a life-cycle state depending on the injected data. Our standard D3 model.</p><h3>Drawing the elements</h3><p>Now we need to write the draw function to get the elements on screen. Let’s just note here that nothing has happened yet — we haven’t called databind() yet because we need to find a way to draw it to the canvas first. So here we go... The draw() function doesn&#39;t need to take any arguments in our case:</p><pre>function draw() {</pre><p>As fleetingly mentioned above, we need to take care of cleaning the canvas every time we draw afresh. The DOM is material, in that when I draw a rect element on it and I change it’s x value, it will move in the x-direction and the DOM will take care of this move (or the -re-paint) automatically. If we move a rect from x = 0 to x = 1 at a certain point in time (after a button press for example) the browser will move the rect from 0 to 1 within one tick or frame-paint (which is roughly 16ms long). If you move it from 0 to 10, it will do so in a time depending on the duration you ordered this transition to be, maybe 1 pixel per tick maybe 8 pixel per tick (for more <a href="https://www.html5rocks.com/en/tutorials/speed/unnecessary-paints/">read this post</a>). But it will tell the pixel at 0 that the rect has disappeared and the pixel at 1 that there is a rect now. Canvas doesn’t do this. We need to tell canvas what to paint, and if we paint something new, we need to tell it to remove the previous paint.</p><p>So let’s start with cleaning up anything that might be on the canvas before we draw. Here’s how:</p><pre>// clear canvas </pre><pre>context.clearRect(0, 0, width, height);</pre><p>Simple.</p><p>Now we…</p><ol><li>get hold of all elements in order to</li><li>loop through all elements and</li><li>take the information we have stored in the databind() function to draw the element:</li></ol><pre>// draw each individual custom element with their properties </pre><pre>var elements = custom.selectAll(&#39;custom.rect&#39;) <br>// select all our custom elements</pre><pre>elements.each(function(d,i) { </pre><pre>  // for each virtual/custom element... <br>  var node = d3.select(this); // each individual element in the loop </pre><pre>  // apply colour  <br>  context.fillStyle = node.attr(&#39;fillStyle&#39;); <br>  </pre><pre>  // and here we draw the square  <br>  context.fillRect(node.attr(&#39;x&#39;), node.attr(&#39;y&#39;),   <br>                   node.attr(&#39;width&#39;), node.attr(&#39;height&#39;))</pre><pre>}); // loop through each element</pre><p>And that’s it ! We can close the draw() function</p><pre>} // draw()</pre><p>When starting with canvas after some time wanting to dive into it, this simplicity really upped my spirits.</p><p>However, we haven’t done anything yet. We have the tools in the databind() and the draw() function but we haven&#39;t drawn yet. How do we do this? If we just wanted to draw a static visual or image, we would just call</p><pre>databind(data); <br>draw();</pre><p>This would bind the data to the custom elements which would live in memory and then draw it — once !</p><p>But we have transitions. Remember above when we wrote our update function we transition the cell width and height from 0 to their size as well as the colour from black (the default) to the respective element’s colour. A default D3 transition lasts 250 milliseconds, so we need to redraw our squares many times in these 250 ms in order to get a smooth transition. How do we do this?</p><p>It’s again simple. We just call databind(data) to create our custom elements before we repeatedly call draw() as long as it takes for the transition to run. So in our case at least 250 ms. We could use setInterval() for this but we really should use the powers ofrequestAnimationFrame() in order to be as performant as possible (for more <a href="https://css-tricks.com/using-requestanimationframe/">read this</a>). There are a few ways to use it, but keeping within the D3 spirit, I&#39;ll use d3.timer() which implements requestAnimationFrame() as well as being straight forward to use. So here we go:</p><pre>// === First call === // </pre><pre>databind(d3.range(value)); // Build the custom elements in memory </pre><pre>var t = d3.timer(function(elapsed) { </pre><pre>  draw(); </pre><pre>  if (elapsed &gt; 500) t.stop(); </pre><pre>}); </pre><pre>// start a timer that runs the draw function for 500 ms (or anything slightly higher than the transition time for our custom elements)</pre><p>d3.timer() calls the callback repeatedly until elapsed (which is the passed time in milliseconds from instantiation) is past 500 and then the timer is stopped. In these 500 milliseconds, it runs the draw() at each tick (roughly each 16ms). draw() then looks at each element&#39;s attributes and draws them accordingly.</p><p>Note that draw() needs to come right after the databind() function. We couldn&#39;t ask the machine to run databind(), then do something else for a second and then call draw() as after 1 second the transitioned states calculated by our databind() function have all transitioned already - done, dusted and forgotten.</p><p>That’s it ! We’ve bound data to custom elements and we’ve drawn it to the canvas.</p><h3>Let the user update the number of squares</h3><p>In order to give the user the chance to repeat this feat with a custom number of elements (ok, semi-custom with a maximum of 10k) we add the following listener and handler to our text-input box:</p><pre>// === Listeners/handlers === //</pre><pre>d3.select(&#39;#textinput&#39;).on(&#39;keydown&#39;, function() {</pre><pre>  // Only do something if the user hits return (keycode 13)<br>  if (d3.event.keyCode === 13) {</pre><pre>   // if the user goes lower than 1 or higher than 10k<br>    if (+this.value &lt; 1 || +this.value &gt; 10000) {</pre><pre>      // ... highlight the note about the range<br>      d3.select(&#39;#text-explain&#39;).classed(&#39;alert&#39;, true);</pre><pre>       return;</pre><pre>     } else { // if the user types in a sensible number</pre><pre>       // remove potential alert colours from the note<br>      d3.select(&#39;#text-explain&#39;).classed(&#39;alert&#39;, false); </pre><pre>      value = +this.value; // set the value</pre><pre>      databind(d3.range(value), colourId); // bind the data</pre><pre>      var t = d3.timer(function(elapsed) {<br>            <br>        draw();<br>        if (elapsed &gt; 500) t.stop();</pre><pre>      }); // start a timer that runs the draw function for 500 ms (this needs to be higher than the transition in the databind function)</pre><pre>     }<br>      <br>  } // keyCode 13 === carriage return<br>      <br>}); // text input listener/handler</pre><p>Here it is again, our colourful grid of canvas squares, ready to be updated and redrawn:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/0*o6kFrYtJxoly167J.png" /></figure><p><a href="http://blockbuilder.org/larsvers/d187337850d58a444082841c739985ca">Here’s the full code for this first part</a>. In <a href="http://www.datamake.io/blog/d3-canvas-2">the second part</a> we’ll add interactivity to our little friendly squares. If you can’t wait you can read both posts at <a href="http://www.datamake.io/blog">www.datamake.io/blog</a> and jump directly to <a href="http://www.datamake.io/blog/d3-canvas-full">the full post</a> including a <a href="http://www.datamake.io/blog/d3-canvas-full#manual">the step-by-step manual</a>.</p><p><em>Originally published at </em><a href="http://www.datamake.io/blog/d3-canvas-1"><em>www.datamake.io</em></a><em>.</em></p><p><em>lars verspohl </em><a href="http://www.datamake.io/"><em>www.datamake.io</em></a><em> @lars_vers</em><a href="https://www.linkedin.com/in/larsverspohl"><em>https://www.linkedin.com/in/larsverspohl</em></a></p><p><strong><em>…is always grateful for a like or follow he can return</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7a240a32915" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What would Aristotle say about data stories? The learnings !]]></title>
            <link>https://medium.com/@lverspohl/what-would-aristotle-say-about-data-stories-the-learnings-851f4942bdeb?source=rss-3ed15968ada5------2</link>
            <guid isPermaLink="false">https://medium.com/p/851f4942bdeb</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[visual-storytelling]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[storytelling]]></category>
            <category><![CDATA[communication]]></category>
            <dc:creator><![CDATA[lars verspohl]]></dc:creator>
            <pubDate>Sat, 26 Nov 2016 19:31:01 GMT</pubDate>
            <atom:updated>2016-11-28T08:01:40.933Z</atom:updated>
            <content:encoded><![CDATA[<h4>6 principles for better data visualisation #TL;DR</h4><p>This series humbly looked up to Aristotle asking him how his principles of storytelling (plot, character, thought, diction, song and spectacle) can be applied to, and potentially enhance data visualisation. After an <a href="https://medium.com/@lverspohl/what-would-aristotle-say-about-data-stories-1-49e97c3ce78d#.bmk9m32cj">introduction</a> we’ve covered Aristotle’s 6 principles of storytelling: <a href="https://medium.com/@lverspohl/what-would-aristotle-say-about-data-stories-the-plot-cbcb02afc234#.en2290f2x">plot</a>, <a href="https://medium.com/@lverspohl/what-would-aristotle-say-about-data-stories-character-5c460df9a2cf#.4hn1vo7x7">character</a>, <a href="https://medium.com/@lverspohl/what-would-aristotle-say-about-data-stories-arriving-at-catharsis-c2aebd9882dc#.4fm4tckh9">thought, diction, song, spectacle as well as the story-aim: catharsis</a>. This last post wraps our mission up with some summarising fireworks to take home…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4_tN712xwWUiRL8E.png" /></figure><h3>The visual principles</h3><p>Now then. What has Aristotle to say about data visualisation? I think before he has a chance to answer, it’s important to offer an apology to the gods for flagrantly likening his work, clearly invented for Greek Tragedy, to data visualisation. However, equally humbly I suggest that it is his own fault for writing such a universally valid piece about stories — which are such universally applicable means of communication.</p><p>In order to figure out what he might have to say about it, we first had to establish the communality between poetry and data visualisation which is roughly covered by the term <strong>communication medium</strong> as well as by the shared purpose of changing knowledge, belief, opinion or perspective. We also needed to allow ourselves to stray from the straight path delineated by Aristotle and see it rather as a flexible blueprint and an impulse to focus our thinking on what matters.</p><p>However, acknowledging deviations to the original as well as inviting the common ground, we shall now formulate <strong>7 principles of visual poetics</strong> to support our visual and narrative design process on a conceptual level:</p><h3>1 Stay close to the theme</h3><p>The essence of a visualisation is to perceive the story that the information has to tell. Each story is embraced by context. Each context is summarised by theme. Hence, <strong>theme</strong> is the well and the wall of any communication text. It holds our visualisation together and as such deserves to be the starting point of all consideration and re-visited often. Naturally it will inform the context and our story or stories. Further, it should inform our design to manifest in potential graphical connotations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*zwHCjGIO29QFjp1aOyyoDw.png" /><figcaption>A visual in a context in a theme</figcaption></figure><h3>2 Script a visual plot</h3><p>The plot is of central importance to Aristotle, holding the individual pieces of the play not only together, but also giving it a canonical shape with a beginning and an end. Plot in data visualisation is rightfully contested and can by no means be a rule in the original sense. It can only sometimes follow the strict linearity on a general Aristotelian level but can often help the production process by being aware of micro-plots and the user’s urge to plot the information field together. As such we could openly rename plot as the tangible fabric the producer passes to the reader to create meaning.</p><ol><li>Individual patterns can be read as plots and should be presented linearly and coherently.</li><li>Establish a coherent visual plot striving for unity of content, unity of design and where applicable unity of time in order to focus the read.</li><li>Aim for a suitable magnitude of expression. Often one of the most difficult points in practice, it is important to find the right spot between complexity and simplicity while neither overstraining nor boring your readers.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*sqiVUdhHgVTPGs5GHX7znA.png" /><figcaption>A visualiser finding coherent patterns to visualise</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*TBo3aLCejArenYx9jRRmjw.png" /><figcaption>A reader coming along to take in most of the established patterns and adding her very own knowledge to it</figcaption></figure><h3>3 Design close to your users’ mental models</h3><p>Characters in Aristotle’s Poetics have the task of engaging the audience through empathy. A data visualisation needs to elicit engagement but can’t draw from the same levels of empathy between a human actor and a human audience. Engagement is achieved by good design.</p><ol><li>Appeal to pre-attentive perception through channel effectiveness with <strong>visual design</strong>.</li><li>Tap into existing mental models by using organic or — more broadly — <strong>allegorical design</strong>.</li><li>Be aware of and play to characters or character-like narrative elements with <strong>character design</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Aj3YDUgycR-VUO7_ameAAQ.png" /></figure><h3>4 Constrain your visual diction</h3><p>Aristotle demands poetic diction — the choice of words — to be clear and focused. The essence of the play needs to be represented unswervingly. Equally, visual diction in data visualisation — the choice of elements, marks and channels — needs to represent the essence of the data and the analysis. Work minimally alongside the data; keep the data-ink ratio high; use colour economically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*AeJ02xvuggmsNsip3mbWjw.png" /><figcaption>(dramatised)</figcaption></figure><h3>5 Set the visual tone in the back</h3><p>Aristotle wanted the background choir to set the tone of the story — to actively accompany the proceedings on stage. In visualisations the background often takes up a large part of the screen real estate, but it should not often be a large part of the message. Be certain to keep the background in the background while using it to set the tonality of the visual.</p><h3>6 Use spectacle only to round the corners</h3><p>Spectacle describes the use of effects in order to heighten excitement and surprise. Blunt in nature and external to the essence, they should be used sparingly to not distract from the core experience. Data visualisation can apply additional stylistic features — redundant animations, notes, transitions — as long as they understand their place in the background; as long as they work towards a rounded experience and not compete for the user’s memory.</p><h3>7 Refine your user’s perspective</h3><p>Catharsis describes the process of purging the audience’s emotions, aiming for a re-construction to gain a higher level of understanding. The poetic principles can be a road-map to catharsis. With less emotion, but more cognition-focus, a visual data display aims at a similar result that we named refinement. The principles we shamelessly (yet hopefully with respect) re-configured might describe a framework to produce sustainable perspective refinements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*bIlqrfAaSdqIKDqOF0fLCA.png" /></figure><p>So here we are. 7 principles of visual storytelling, wrapped up in a handy tool-belt — something we have in the under-stairs cupboard to dig out when needed and use when appropriate. No stern rule-book of laws to follow religiously, but rather a box of chocolates to enjoy when we feel like it. Why? Because we’re all stories. sort of.</p><h3>Sources</h3><p>Some of the fabulous sources that can’t be blamed for above mis-conceptions…</p><p><strong>Books · Aristotle, Media</strong></p><ul><li><a href="http://classics.mit.edu//Aristotle/poetics.html">Poetics</a> by Aristotle</li><li><a href="https://www2.cnr.edu/home/bmcmanus/poetics.html">Outline of Aristotle’s Theory of Tragedy in the Poetics</a> by Barbara F. McManus</li><li><a href="https://archive.org/details/freytagstechniqu00freyuoft">Freytag’s Technique of the drama : an exposition of dramatic composition and art</a> by Gustav Freytag</li><li><a href="http://faculty.georgetown.edu/irvinem/theory/Hall-Encoding-Decoding-CSReader.pdf">Encoding, Decoding</a> by Stuart Hall</li><li><a href="https://books.google.co.uk/books?id=Vv_ocJqva_kC&amp;redir_esc=y">The Cultural Studies Reader</a> edited by Simon During</li></ul><p><strong>Books · Visualisation</strong></p><ul><li>Stephen Few’s books, especially <a href="http://www.analyticspress.com/show.html">Show Me the Numbers</a></li><li>Edward Tufte’s books, especially <a href="http://www.edwardtufte.com/tufte/books_vdqi">The Visual Display of Quantitative Information</a></li><li><a href="http://store.elsevier.com/Information-Visualization/Colin-Ware/isbn-9780123814647/">Information Visualization</a> by Colin Ware</li><li><a href="https://www.crcpress.com/Visualization-Analysis-and-Design/Munzner/9781466508910">Visualization Analysis and Design</a> by Tamara Munzner</li><li><a href="http://esripress.esri.com/display/index.cfm?fuseaction=display&amp;websiteID=190">Semiology of Graphics</a> by Jaques Bertin</li></ul><p><strong>Papers</strong></p><ul><li><a href="http://www.datavis.ca/papers/hbook.pdf">A Brief History of Data Visualization</a> by Michael Friendly</li><li><a href="http://vis.stanford.edu/files/2010-Narrative-InfoVis.pdf">Narrative Visualization: Telling Stories with Data</a> by Edward Segel and Jeffrey Heer</li><li><a href="https://www.interaction-design.org/literature/book/the-encyclopedia-of-human-computer-interaction-2nd-ed/data-visualization-for-human-perception">Data Visualization for Human Perception</a> by Stephen Few</li><li><a href="http://kosara.net/papers/2013/Kosara_Computer_2013.pdf">Storytelling: The Next Step for Visualization</a> by Robert Kosara and Jock Mackinlay</li></ul><p><strong>Posts</strong></p><ul><li><a href="http://blogger.ghostweather.com/2014/03/implied-stories-and-data-vis.html">Implied Stories (and Data Vis)</a> by Lynn Cherney</li><li><a href="http://www.periscopic.com/news/a-framework-for-talking-about-data-narration">A Framework for Talking About Data Narration</a> by Dino Citraro</li><li><a href="http://io9.gizmodo.com/5916970/the-22-rules-of-storytelling-according-to-pixar">The 22 rules of storytelling, according to Pixar</a> by Emma Coates</li><li><a href="http://well-formed-data.net/archives/1027/worlds-not-stories">Worlds, not stories</a> by Moritz Stefaner</li><li><a href="https://eagereyes.org/blog/2014/stories-are-gateways-into-worlds">Stories Are Gateways Into Worlds</a> by Robert Kosara</li><li><a href="https://eagereyes.org/blog/2014/story-a-definition">Story: A Definition</a> by Robert Kosara</li></ul><p><strong>Podcasts</strong></p><ul><li>Data stories podcast <a href="http://datastori.es/data-stories-35-visual-storytelling-w-alberto-cairo-and-robert-kosara/">Visual Storytelling</a></li><li>Data stories podcast <a href="http://datastori.es/69-data-visualization-literacy-with-jeremy-boy-helen-kennedy-and-andy-kirk/">Data Visualization Literacy</a></li></ul><p><em>Originally published at </em><a href="http://www.datamake.io/blog/visual-poetics-5"><em>www.datamake.io</em></a><em>.</em></p><p><em>lars verspohl </em><a href="http://www.datamake.io/"><em>www.datamake.io</em></a><em> @lars_vers </em><a href="https://www.linkedin.com/in/larsverspohl"><em>https://www.linkedin.com/in/larsverspohl</em></a></p><p><strong><em>…is always grateful for a like or follow he can return</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=851f4942bdeb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What would Aristotle say about data stories? Arriving at Catharsis!]]></title>
            <link>https://medium.com/@lverspohl/what-would-aristotle-say-about-data-stories-arriving-at-catharsis-c2aebd9882dc?source=rss-3ed15968ada5------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2aebd9882dc</guid>
            <category><![CDATA[communication]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[storytelling]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[visual-storytelling]]></category>
            <dc:creator><![CDATA[lars verspohl]]></dc:creator>
            <pubDate>Mon, 21 Nov 2016 18:26:01 GMT</pubDate>
            <atom:updated>2016-11-21T18:26:01.028Z</atom:updated>
            <content:encoded><![CDATA[<h4>6 principles for better data visualisation #3–6</h4><p>This series humbly looks up to Aristotle asking him how his principles of storytelling (plot, character, thought, diction, song and spectacle) can be applied to, and potentially enhance, data visualisation. So far, we’ve covered <a href="https://medium.com/@lverspohl/what-would-aristotle-say-about-data-stories-the-plot-cbcb02afc234#.7tkdnq3nc">plot</a> and <a href="https://medium.com/@lverspohl/what-would-aristotle-say-about-data-stories-the-plot-cbcb02afc234#.7tkdnq3nc">character</a>. In this post we’ll have a look at principles 3,4,5,6 before arriving at the story-purpose: <em>catharsis</em>.</p><h3>Thought</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*7jYJg8Gj7hZp9yNADdpYnw.png" /></figure><p>Next is thought. Aristotle is a little coy or rather mystic about it but let’s assume he means what the world thinks he means: <strong>theme</strong>. Vengeance in Troy, love in Romeo and Juliet, philanthropy in Ice Age. The theme taps into the 3 before mentioned sub-principles of unity, magnitude and universality. A theme consistently pursued creates a meta-unity of story — a theme being expressed by a variety of plot-events and mirrored by characters adds magnitude. As such a theme can raise the play to a higher order of message, in the sense that</p><p><strong><em>..the story is more valuable than the sum of its plot-events.</em></strong></p><p>Why is that? Because a story is an interaction between the plot and the audience. The audience enriches the plot with their very own world-knowledge and context, tickled out by the theme.</p><p>Theme applies to both story and context. Theme is the nucleus of a play, a film, a book and a data visualisation. It holds it together and should be visited often times when producing any of the above. It provides conceptual unity, a backbone to the piece. A strong theme allows more freedom in plot-construction as it can hold together distant parts of the plot. As such it’s a tool for the producer. Yet while producers have more or less natural copyright on the plot or the manifestation of their text, they have to share the theme with the reader. Although the actual information displayed in the visual might be new, the theme discussed will most likely not be. Views, knowledge, beliefs will already be in place and will very much mingle with the thematic interpretation of the text.</p><p>The theme of the <a href="http://www.nytimes.com/interactive/2015/09/30/business/how-the-us-and-opec-drive-oil-prices.html">NY Times visualisation</a> we have visited before is control. Three forces in the form of the incumbent OPEC, the challenger US as well as the more elusive force of political events with global impact determine two metrics: oil price and oil production. The New York Times decided to explain this visually with a connected scatterplot. One could have shown it differently. But whatever way we show it the theme would remain. Fictional media often plays with the theme. It’s not overtly revealed and serves as an elusive thread through the text that gets pieced together slowly by the reader. For informative visualisations, it may help to clarify the theme openly in order to activate the reader’s contexts up front. For the design process of a complex visual — explanatory but also exploratory — a constant awareness of the theme supports design- and thematic coherence.</p><h3>Diction</h3><p>Diction — Aristotle’s fourth principle of storytelling — is an interesting one from our perspective. It’s basically <strong>style</strong>. The style of the words to be more precise. He warns about the usage of metaphors and ‘rare’ words. Overusing metaphors can keel over to a riddle and unusual word-use to crypto-jargon no one follows voluntarily.</p><p>You don’t need to leaf through many pages of any standard data visualisation work to get warned about bells and whistles. Discipline in the use of <a href="http://www.infovis-wiki.net/index.php/Data-Ink_Ratio">data-ink</a> is mandatory (even in the screen-age) and the purposeful focus on the necessary shall lead to a streamlined and non-distracting design.</p><p>Little Diction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/0*ldoAYph4XZmDqrk7.png" /></figure><p>More Diction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VVuGcbFUypB3TR46.png" /></figure><p>Little Diction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/0*S2i_frrG9S-X9Ixe.png" /></figure><p>More Diction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JlEBJ7J1bPqIuNHF.png" /></figure><p>What I did here was to take away the all-to-eager decoration of the information in order to establish a clear understanding of the information. Maybe I was a little too purist — one could use pictograms to show the costume categories or flags and a more ‘cosmetic colour-setting’ in the second example. Yet, the visual diction should not obstruct or even falsify the information.</p><p>But wait, I say? We just established that metaphors are welcome as they can arouse engagement which — if not used — could lead to a smaller readership or lesser impact of our visual. Now we are told to speak clearly and directly avoiding exactly the metaphors we were hailing above. And it’s true — the line is fine. A simple visualisation which does not need to bootstrap significant amounts of engagement, but can be read fleetingly, should be as concise and focussed as possible. A more complex visualisation, which requires time to decipher, can use allegorical design to draw in the reader. An additional level of interactivity like in the <a href="http://www.oecdbetterlifeindex.org/">OECD Better life index</a> can produce non-metaphoric interpretations of the same pattern if possible.</p><p>Get the gist with organic design</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gG_jicOJSeca-4t5.png" /></figure><p>Get precision with efficient design</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JCMuUhLi7-GLf_Id.png" /></figure><h3>Song</h3><p>Aristotle’s number 5 is Song or Melody and accompanies Diction in the sense that it is a stylistic engraving — even more so than Diction. While Diction — or the style of the words used — can be a valid, even essential actor of the play and plot, song is more of an embellishment, an engraving, an ambient tapestry — necessary but imaginable in various forms without doing too much harm; a <strong>stylistic hygiene factor</strong> of sorts, as it would hurt if not used but remains in the background when used. However, Aristotle demands the song to be more than that. It should not only be mere background, it should be an active agent in the play claiming a role and driving the plot.</p><p>For Greek plays of Aristotle’s time we have to imagine a background choir accompanying the proceedings with an appropriate tonality. The aim was to subtly reinforce but not drown out the dramatic events on stage. In data visualisation it is the stylistic setting that represents this tonality. This includes all design elements that build the background for the data-shapes like colour schemes, containers, fonts, weights, etc.</p><p>For a statistical graph in an academic paper, tonality should be neutral. A colour scheme of white, grey and a few hand picked functional colours with a clean serif font; headlines set apart from annotations via font-size and -weight. For more journalistic or narrative pieces a different tonality can be set. <a href="https://medium.com/u/58804dc28919">Periscopic</a>’s <a href="http://guns.periscopic.com/?year=2013">Gun Death</a> visualisation probably purposefully chose a black background with slow transitions for title and controls to support the topical gravitas. Kiln’s interactive <a href="http://www.wri.org/resources/data-visualizations/carbon-emissions-past-present-and-future-interactive">Carbon Emissions Past, Present and Future</a> also finds a specific tonality in a simplified near cartoon-like background signalling simple explanations in a topical setting.</p><p>Periscopic · Gun Deaths</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AofDFYOVSkNem4sl.png" /></figure><p>Kiln · Carbon Emissions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/0*wmTch1LJ7Xqlr23-.png" /></figure><h3>Spectacle</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*s4tZwK-nlzFUrsBJ.gif" /></figure><p>These days probably called <strong>special effects</strong>, Spectacle is not apportioned to the poet. Aristotle recognises it as the job of the <em>stage machinist</em> (good title) to support the plot with spectacle in order to generate emotions. External and surprising, underlining and loud, the spectacle, the ‘stylistic effects’ are supposed to help emotions to bloom. He acknowledges the spectacle as a means to an end, which, however, should rather be reached by plot and character. The main reason for his scepticism is that spectacle is a blunt tool. It shocks rather than subtly moving under the skin. As it is external by definition — neither naturally evolving from plot or character nor remaining in the background like ‘Song’ — it finds it hard to dock onto the viewers’ inner self, to reach empathy and trigger engagement.</p><p>Again, Aristotle underlines the focus on the essence shining through in most of his principles, most evident in his deliberations about Diction. Where’s the difference? Diction is concerned with the very fabric of the play, the spoken word. In data visualisation this fabric is produced by the shapes and their styles — form, colour, weight, orientation. Spectacle is external to text. The text can live as such — the spectacle can’t. Spectacle has supporting character. A visualisation can live without an initial animation. A transition is often very much part of the text in serving <a href="https://bost.ocks.org/mike/constancy/">object constancy</a>. This would indeed be a decision of visual diction. However, an initial animation into space, or a transition from one graph into another, popping network-nodes before moving on to an alternative display is spectacle. In visualisation these strictly superfluous effects don’t necessarily propel the cause of the display, yet they can turn the display into a fluid one, a round corpus or text, improving the experience of the reader. As such they are invited as long as they remain in the background, understanding their supportive role and not burning any valuable time.</p><p>Bad spectacle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*GgwLa3l746aOxy5M.png" /></figure><p>See the arcs and ‘explosions’? Good spectacle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*ygP_V6tzS_c6-ip8.gif" /><figcaption><a href="http://www.datamake.io/blog/%E2%80%9Dhttp://drones.pitchinteractive.com/%E2%80%9D">Out of Sight, Out of Mind</a> by Pitch Interactive</figcaption></figure><p>Right then. We have reached the end of our principle trip and shall eventually tie it up with what Aristotle would call the aim and the very purpose of every tragic story…</p><h3>Catharsis</h3><p>In fact, Aristotle doesn’t define Catharsis in his works, yet he uses it enough to let us derive a definition. There are two main definitions:</p><ol><li><strong>The literal one</strong> — closest to his examples — describes the healing effect a tragedy has by chucking us into the deep end of our emotions, re-surfacing purified, purged and renewed, with a better understanding of emotions such as pity and fear.</li><li><strong>The lateral one </strong>— established in the 20th century — speaks of an intellectual clarification. The audience partakes in a representation of reality and the mixture of distance and proximity creates a space of intellectual pleasure and inference. We reach higher levels of understanding through reality simulations. It’s how children learn through games.</li></ol><p>In both cases, catharsis operates on the meta-level of the text. It is the process of learning from a play.</p><p>This is the purpose of a text — the purpose of communication. Aristotle’s ideal play wants to educate, to make the viewer understand and learn, change perspectives, ideas, opinions or beliefs. We should equally judge the text ultimately by how well it achieves a change of mind. In the case of Aristotle’s plays catharsis first purges us of existing emotions in order to re-assemble them in a part-conscious way. In data visualisation we rarely want to change emotions, but always knowledge. We also don’t necessarily need to tear down existing knowledge, yet often aim at building new knowledge. Stephen Few summarises:</p><blockquote><a href="https://www.interaction-design.org/literature/book/the-encyclopedia-of-human-computer-interaction-2nd-ed/data-visualization-for-human-perception">we should always judge a visualisation’s merits by the degree to which we can easily, efficiently, accurately, and meaningfully perceive the story that the information has to tell.</a></blockquote><p>For want of a better word, data visualisation should not necessarily aim to be cathartic, but <strong>refining</strong>.</p><p>By creating a fabric of data-driven meaning, creating structures of narratives where applicable, designed for unclogged visual consumption, focussing style and content on engaging essentials, we aim to build a new or at least modified and hopefully lasting perspective.</p><p><strong>To put it simply: we design visual data displays that read clearly, engage continuously and refine perspectives sustainably.</strong></p><p>Well, then. We have visited all of Aristotle’s principles of storytelling from Plot to Character to Thought, Diction, Song and Spectacle and arrived at Catharsis, the audience-changing purpose of a story. In the final post I shall try to summarise them to a more comfortable tool-belt we can easily don when building visual displays. A kind of Aristotelian cheat-sheet…</p><p>Next post, next week, same time, same place…</p><p><em>lars verspohl </em><a href="http://www.datamake.io/"><em>www.datamake.io</em></a><em> @lars_vers</em><a href="https://www.linkedin.com/in/larsverspohl"><em>https://www.linkedin.com/in/larsverspohl</em></a></p><p><strong><em>…is always grateful for a like or follow he can return</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2aebd9882dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What would Aristotle say about data stories? Character !]]></title>
            <link>https://medium.com/@lverspohl/what-would-aristotle-say-about-data-stories-character-5c460df9a2cf?source=rss-3ed15968ada5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c460df9a2cf</guid>
            <category><![CDATA[storytelling]]></category>
            <category><![CDATA[visual-storytelling]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[communication]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[lars verspohl]]></dc:creator>
            <pubDate>Mon, 14 Nov 2016 16:41:01 GMT</pubDate>
            <atom:updated>2016-11-14T16:41:01.406Z</atom:updated>
            <content:encoded><![CDATA[<h4>6 principles for better data visualisation #2</h4><p>This series humbly looks up to Aristotle asking him how his principles of storytelling (plot, character, thought, diction, song and spectacle) can be applied to, and potentially enhance, data visualisation. So far, I’ve collected <a href="https://medium.com/@lverspohl/what-would-aristotle-say-about-data-stories-1-49e97c3ce78d#.yksrtfvvj">initial thoughts</a>, and <a href="https://medium.com/@lverspohl/what-would-aristotle-say-about-data-stories-the-plot-cbcb02afc234#.wx03t2jge">wrote about one of his key principle: Plot</a>. This post will look at his second — also truly crucial principle: <em>character..</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*5MyTTR_Rifdje0pA.png" /></figure><p>Character is the second key principle in Aristotle’s considerations alongside <em>Plot</em>. Aristotle’s characters have a rather pre-determined trajectory from prosperous to abandoned; the classic tragic course. The fortunes need to collapse from good to bad, brought about by a character weakness or — and this is preferred — by a lack of knowledge. Both seeds of doom are ones we’re all acquainted with and can relate to. This character’s flight path, Aristotle suggests, is the safest recipe to tie in the audience’s pity and fear of the same fate.</p><p><strong>The character’s main task is to tie in the audience’s emotions through empathy.</strong></p><p>He or she falls from fame to shame. And so do we. We identify with a strong character to begin with and learn our lesson on the way alongside the protagonist. Empathy, our capacity to step into the protagonist’s shoes, ropes us in. The more empathy we allow for the character, the more likely we will be to learn from the play.</p><p>Now then. This character classification is too specific to apply to data visualisation as such. Data is not human; it’s abstract. We can’t put ourselves into the emotional reference frame of a datapoint. We can indeed create emotional ties to data representing human emotions — <a href="https://medium.com/u/58804dc28919">Periscopic</a>’s <a href="http://guns.periscopic.com/?year=2013">Gun Deaths</a> establishes an emotional link with a curated animation about lost years due to gun crime in the US. But by no means can this be a universal principle to be applied in data visualisation.</p><p><strong>What we can and should establish is <em>engagement</em>. Not so much as a function of empathy but as a function of good design</strong>.</p><p>Aristotle’s protagonist, who successfully ropes in the audience, is good design. The character is designed for human understanding, so that we can take her perspective. Sometimes visualisation presents character, often it presents abstract concepts. But our final goal remains the production of knowledge and meaning and we can only achieve that by users buying into the visualisation.</p><p>Having said that, it appears that one of the key problems we face in data visualisation — more so than in other communication media — is medium specific literacy on the reader’s part. Data visualisation literacy is part data literacy (= number sense) part visual literacy (= visual perception, experience and accuracy). In order to get to our final goal of knowledge and meaning production we need to win the reader’s commitment to (1) look at the visual (2) learn to read the visual (3) interpret the numbers and finally (4) learn or understand something from the numbers. That’s often a big ask — sometimes even for a simple bar chart. In order to help understanding we want to make our visualisations easily accessible, comparable and relatable; or to put it more generic we want to use <strong>visual design</strong>, <strong>allegorical design</strong> and <strong>topical </strong>or <strong>character design</strong>…</p><p>While a single visualisation won’t be able to instil statistical foundations, we can use …</p><p>..visual design to communicate data with as little perceptive burden as necessary,</p><p>..allegorical design to activate existing mind models as well as</p><p>..character design to enable human connections.</p><h4>Visual Design</h4><p>We achieve a proficient <strong>visual design</strong> by rules of channels effectiveness (see <a href="http://image.slidesharecdn.com/5summaryihub-150728082235-lva1-app6891/95/data-visualization-summary-ihub-63-638.jpg?cb=1438071933">here</a> or <a href="https://www.cs.ubc.ca/~tmm/courses/cpsc533c-04-spr/readings/cleveland.pdf">here</a> and the <a href="https://en.wikipedia.org/wiki/Gestalt_psychology#Gestalt_laws_of_grouping">gestalt laws</a>). There’s a lot being written about most proficient and sensible visual design, so I’ll keep this short here. But by spending a lot of time thinking about it we allow an easy connection between concept and reader.</p><h4>Allegorical Design</h4><p><strong>Allegorical design</strong> tries to liken our dataset visually to already known concepts in nature or elsewhere. It is about producing natural reflections in our visuals. This can be as simple as using natural colour schemes or encoding information in organic design that the human eye reacts kindly to as it compares with the known natural.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/0*4wb2XD-xqTyffBht.png" /></figure><p><a href="http://notabilia.net/">Notabilia</a> by <a href="https://medium.com/u/f50f8c4bbcbd">Moritz Stefaner</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/0*aKBjbjNRFcMLzXAL.png" /></figure><p><a href="http://giorgialupi.com/work#/amazons-data-come-to-life/">A Study in Scarlet</a> by <a href="https://medium.com/u/2b468a91df0f">giorgia lupi</a>/Accurat</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/0*BtIT4m6zdFlmd-O5.png" /></figure><p><a href="http://www.stefanieposavec.co.uk/-everything-in-between/#/entangled-word-bank/">(En)tangled Word Bank</a> by <a href="https://medium.com/u/c469efa814bc">Stefanie Posavec</a></p><h4>Character Design</h4><p>Finally — and this can’t always be the case — we can attempt to apply an effective <strong>character</strong> <strong>design</strong> by means of spending time and space to characterise people or forces that are part of the visualisation. Going back to the <a href="http://www.nytimes.com/interactive/2015/09/30/business/how-the-us-and-opec-drive-oil-prices.html">NY Times oil price visual</a> we visited in the last post, the US and OPEC are set up as two players on the field. No empathy in the literal sense, but my involvement in the piece is raised by the focus on two forces who propel events with actions. When producing our visuals around characters or character-like units, the readers will negotiate their very personal position to both, the US and the OPEC against the backdrop of nationality, personal view about shale oil and politics of the involved parties/countries/characters.</p><h4><strong>What else?</strong></h4><p>Another often helpful path to engagement is telling the story of the data exploration. Where did the data come from? How difficult was the cleaning process? What did I expect — what surprised me? Any schoolboy-errors on the way? And how did I finally got to the results? The best documentaries often have very strong narrators !</p><p>Overall it helps to keep this role of character in mind and probe for the opportunity to sketch out characters — even non-human characters — to introduce engagement.</p><p>The goal of all 3 design concepts — visual, allegorical and character design — is to achieve increased engagement that clears the high hurdle of reading and memorising the data. Engagement buys patience to learn the visual, which promotes understanding and potentially a changed perspective.</p><p>With plot and character in the bag, the next task is to look at all the remaining concepts… Moving quickly now !</p><p>Next post, next week, same time, same place…</p><p><em>lars verspohl </em><a href="http://www.datamake.io/"><em>www.datamake.io</em></a><em> @lars_vers </em><a href="https://www.linkedin.com/in/larsverspohl"><em>https://www.linkedin.com/in/larsverspohl</em></a></p><p><strong><em>…is always grateful for a like or follow he can return</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c460df9a2cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What would Aristotle say about data stories? The plot !]]></title>
            <link>https://medium.com/@lverspohl/what-would-aristotle-say-about-data-stories-the-plot-cbcb02afc234?source=rss-3ed15968ada5------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbcb02afc234</guid>
            <category><![CDATA[design]]></category>
            <category><![CDATA[storytelling]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[visual-storytelling]]></category>
            <category><![CDATA[communication]]></category>
            <dc:creator><![CDATA[lars verspohl]]></dc:creator>
            <pubDate>Mon, 07 Nov 2016 09:40:14 GMT</pubDate>
            <atom:updated>2016-11-09T14:56:56.681Z</atom:updated>
            <content:encoded><![CDATA[<h4>6 principles for better data visualisation #1</h4><p>This series humbly looks up to Aristotle asking him how his principles of storytelling (plot, character, thought, diction, song and spectacle) can be applied to, and potentially enhance, data visualisation. After a brief <a href="https://medium.com/@lverspohl/what-would-aristotle-say-about-data-stories-1-49e97c3ce78d#.7mv8ir1ey">introduction</a> in the last post let’s put some feathers on the bird by looking at Aristotle’s first principle: Plot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*Lhj6-FvglajwDnhGkj2Vxg.png" /><figcaption>..and we shall do this modestly, cap-in-hand..</figcaption></figure><p>Plot, the first and most important principle, describes the arrangement of the story’s building blocks. It’s the structure, the narrative, the sequencing of a story. What comes first, what then, what last. Freytag’s Triangle pours this into a simple, if idealistic shape:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OKHXtM-U_Xaor22GRZ_u5w.png" /><figcaption>(Freytag’s bump this is rather)</figcaption></figure><p>It’s a beginning — a middle — an end. Nursery rocket science. The way each part is connected to the chain of events is important: The exposition has to stand on its own legs. What happened before is downplayed; the focus is on the events to come. The middle part is infused by the beginning and propels towards the end. The end looks back rather than forward. It wants closure.</p><p>The concept of a plot promotes one crucial story characteristic that’s truly useful for our mission: it offers a backbone structure to which we can attach meaning relatively easily. Each story acts as a little memory-chain, sensibly connecting pieces of information that are harder to remember on their own. <strong>The story is greater than the sum of its parts.</strong> How does it do this efficiently? Through drive, unity and magnitude…</p><h4>Plot-drive</h4><p>The plot is driven either by <strong>cause and effect</strong> or by a <strong>character</strong> and their personality. Aristotle is quite a frank supporter of the former: the cause and effect. This is owed to the plays of his time that rather centred on a topic than a character. Times have changed a little in literature and drama but let’s note that the sequence of events as well as characters within this trajectory drive a plot forward.</p><p>There are 2 levels of cause-and-effect-(like) drive in visualisations: on the visual micro-level and on the conceptual macro-level. The former is literally inscribed into the very definition of visualisation:</p><p>Visualisation is driven by patterns. That’s what a visualisation technically is — it’s a sensible arrangement of data patterns encoding information in graphical marks and perception channels. There are numerous patterns to represent like time-series, clusters, comparisons, networks, etc. but all patterns relate at least two pieces of information to each other. While true causality between the data is rare, a dependency not acted out conceptually but tangibly drawn on the canvas can invoke a very strong adhesive between different regions of information.</p><p>Chart types predestined for plot-like developments are line charts, flow diagrams or connected scatterplots that convincingly invite the viewer to follow an often linear trajectory with data-points on the way linking data in a propelling form.</p><p>On the conceptual macro-level we can come quite close to Aristotle’s ideal, considering ‘the stepper’, a narrative technique used in more presentational data visualisations. An extension or variation of the stepper is ‘the scroller’ which has the same effect, namely moving from one display to the next display controlled by the reader (some might say <em>scrollytelling</em>). The stepper itself doesn’t unfold any cause and effect, but it forms the structure with which to do</p><p><a href="http://www.nytimes.com/interactive/2015/09/30/business/how-the-us-and-opec-drive-oil-prices.html">The New York Times’ visual</a> How the U.S. and OPEC Drive Oil Prices combines both levels of cause-and-effect-drive by displaying a connected scatter-plot within a stepper-setting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*r5FYFiWJlSxhuNCYW6K6wg.gif" /><figcaption><a href="http://www.nytimes.com/interactive/2015/09/30/business/how-the-us-and-opec-drive-oil-prices.html">How the U.S. and OPEC Drive Oil Prices</a> by Jeremy Ashkenas, Alicia Parlapano and Hannah Fairfield</figcaption></figure><p>The context of the visual piece is control of the oil price development over time; the story is the rise of the US to a global oil power exploiting shale oil. While the connected scatterplot literally drives the development through time, spanning an arc of increasing and then falling prices, the stepper drives the development of characters: mainly the OPEC countries and the US. As this story is split in 2 levels of narrative, the temporal level through the connected scatterplot as well as the character level through the stepper, there are also 2 parallel plot-lines: the development of the metrics’ oil-price and oil-production and the events and characters influencing the metrics. Cause and effect.</p><p>Moving back and squinting our eyes we can further uncover a 3-parted plot-structure with an exposition, a middle part and a conclusion. The plot’s exposition stretches from step 1 to step 3 inclusive. It covers the general arc of the connected scatter showing a global overview from 1996 to the spike in 2011, then zooming in to individual patterns, one after the other. Starting with the rule of the OPEC step 4 introduces what one could nearly call a plotpoint and transitions into a middle part of rising action starting at step 6. We leave the overview and re-start the journey in April 1996. During steps 8 to 11 we are part of literally rising action as events like China’s emergence and the Iraq War boost prices and the financial crisis reduces prices. At step 12 of 14 we enter the final part, now focussing on the key topic: the US impact on the oil price. The final step 14 allows an outlook for a changed future in the annotation while the visual focuses on the current status against the opaque data backdrop of the past 20 years.</p><h4>Plot-unity</h4><p>The second key requirement for an Aristotelian plot is <strong>plot-unity</strong>. The atomic pieces of the plot should be kept in a sequence. They are supposed to relate to each other, to lead to each other, drive each other, be in some sort of chain. The Aristotelic ideal stresses the importance of a single plot (unity of action), a single location (unity of place) and a single day (unity of time). The opposite of a united plot would be an episodic plot. <a href="https://en.wikipedia.org/wiki/Magnolia_(film)">Magnolia</a>, <a href="https://en.wikipedia.org/wiki/Night_on_Earth">Night on Earth</a> and (in parts) the <a href="https://en.wikipedia.org/wiki/Iliad">Illiad</a> — all episodic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*67o61bzR_RBACVLdqNIaCw.png" /></figure><p>Plot-unity aims at a coherent, dense and undistracted experience for the audience. The audience shouldn’t spend time puzzling together the individual pieces, but should be immersed in the story (context) for the message to unfold effortlessly. There are of course clever alternatives in theatre, literature and film. <a href="https://en.wikipedia.org/wiki/Memento_(film)">Memento</a> unfolds the story through exactly the opposite, plot-disunity. A data visualisation can try to be Memento. Often, however, it makes sense to help the reader’s understanding by presenting the story or the context in a unified manner.</p><p>Let’s try and abstract Aristotle’s unities to data visualisation. But let me be clear: right at the start he confronts us with the most difficult principle to abstract and the most (rightfully) contested principle to apply to data visualisation. The graphical layout of information often is not and should not be linear. 2 important side-notes:</p><p>1. While the information encoding is often not linear, the decoding on the recipient’s side often is. We look at a mess and we strive for clarity and patterns, plot-like creatures that might follow the same principles as Arsitotle’s plots. Take for example what we make of an anti-linear plot like Memento’s — we actively re-arrange it into a linear plot.</p><p>2. Even in displays presenting <a href="http://well-formed-data.net/archives/1027/worlds-not-stories">worlds</a> (and I’m totally with Moritz Stefaner on this), I’d argue it is helpful for the producer to have an eye for micro-plots, often the building blocks of a larger exploratory display.</p><p>Yet, the plot can’t be a rule. It of course can be the main structure of a visual (as we see with the NY Times piece), but often it is the road to discovery, or it exists as micro-units, or it just unfolds on the user’s side as a means of bringing order to an open field of information.</p><p>Hence, shamelessly adjusting Aristotle’s principles, I’d like to formulate a suitably broad definition which should incorporate a <em>unity of content</em>, a <em>unity of form</em> and a <em>unity of time</em><strong> </strong>whenever applicable (!). All unities try to focus and convey the message for simple reception. <strong>Unity of content</strong> conditions the accompanying report to be coherent. This can be achieved by a linear, sequential plot as described previously and manifests itself in headlines, annotations, sub-texts, voice-overs, tooltips etc. <strong>Unity of form</strong> defines the design of the visualisation, the shapes, marks, channels, colours and setting. We shall return to this later. The unity of content is significantly broader but contextually similar to Aristotle’s unity of action, while the unity of form resembles his unity of place. While unity of content and form are prerequisites for any visualisation, <strong>unity of time</strong> should be adhered to whenever time is a factor. The Aristotelian definition of a day is obviously very much leaning towards Antique Tragedy, but thought is required to build a coherent temporal space even outside Antique Tragedy. For a time-series this of course is best achieved by a sequence with the starting point before the end point.</p><p>The New York Times’ oil price piece establishes all three sub-principles through a number of means. Unity of content is achieved by two story-lines. First, the overview introducing the main characters and the thematic context. Second, the detailed sub-patterns in a sequential time-line ending at the current state of affairs with the US having become an established oil-power. Unity of form is established through coherent use of the design elements guiding perception along the analysis. The New York Times uses scrollable transitions from note to note, arrows for the connected scatter-plots, labels as well as colouring for the years as well as element- and axis-transitioning between states to secure object-constancy. Time unity is secondary in the NY Times visual as the story is told twice but maintained in both time-lines, once top-line as the overview, once low-level concerned with the individual events.</p><p>The means of establishing unity are key in data visualisation. Opening up the playing field beyond plots, a unified design should not only be at play in explanatory, presentational visualisations, but also in exploratory visuals that enable discoveries. <a href="http://project-ukko.net/">Project UKKO</a> from <a href="https://medium.com/u/f50f8c4bbcbd">Moritz Stefaner</a> is by no means a linear data visualisation telling a canonical story about wind predictions for the upcoming months. It is exploratory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QHqntOTBUdXB7dGpu1Ph5A.png" /></figure><p>It creates a context in which the user can lookup information or discover patterns. Bringing enough personal knowledge to the table (alas, I’m no wind-expert) I would potentially wrap the patterns in story-like units. However, in any case the interplay of angle, thickness and colour create a visual unity of the map elements; the interplay of colour, transitions and lines to the predictions allow a unity of the additional information display at the bottom of the page. This design supports pattern discovery which act as micro-plots to facilitate story abstraction on the user’s side.</p><h4>Plot-magnitude</h4><p>Finally, there is <strong>magnitude</strong>. Aristotle demands certain magnitude from the plot — in length and complexity as well as in universal significance. A plot will gain value, the richer in meaning it becomes. The more the author manages to introduce a certain level of complexity in an organic unity, the more universally significant the play and the more involved the audience will be.</p><p>The holy grail of data visualisation is elegantly to represent the right number of relevant variables. We can visualise a single number, and we can visualise a hairball. But the gods smile upon us when we manage to represent a complex context or story in a succinct way. An obvious example of excellence in this field is <a href="https://en.wikipedia.org/wiki/Charles_Joseph_Minard#Work">Charles Minard’s</a> map of the Russian campaign, where he masterfully manages to marry 6 variables with the reader’s knowledge to conjure up a plot of great complexity, magnitude and universal significance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V9sq--wHI1wm1zA3Gng1sg.png" /><figcaption>Minard’s map showing geo-position, troop size, direction, distance, time and temperature</figcaption></figure><p>Minard’s map is a fantastic example of how visualisations can unfold stories through a very distinct, unified plot of magnitude. The line our eyes follow embodies a clearly linear, unified plot adorned with plotpoints at crucial moments along the way. The varying thickness tells the most important story, leading the eye from the Niemen river to Moscow and back, through a monumentally humbling experience triggered by visual variables. How much story we produce with context we bring to the plot varies depending on where we come from, how much of ‘War and Peace’ we’ve read and how keen a historian we are.</p><p>Right. That took a moment, but <strong>plot</strong> needed some ink as it is probably the most central principle in Aristotle’s rule-book. While we certainly can’t carbon-copy Aristotle’s thoughts for our ideas concerned with visualisation, <em>plot</em> can be a framework to work with on a micro-level of our designs and charts as well as on a macro-level when conceptually conceiving of a visual data representation. <em>Plot-drive</em>, <em>Plot-unity</em> and <em>Plot-magnitude</em> can function as background-concepts we can decide to apply to varying degrees.</p><p>We’ll move a little quicker now with the next post about <strong>character</strong> also taking a single (yet shorter) post, before we’ll look at the remaining principles <em>thought</em>, <em>diction</em>, <em>song</em> and <em>spectacle</em> in one post altogether…</p><p>Next post, next week, same time, same place…</p><p><em>lars verspohl </em><a href="http://www.datamake.io/"><em>www.datamake.io</em></a><em> @lars_vers </em><a href="https://www.linkedin.com/in/larsverspohl"><em>https://www.linkedin.com/in/larsverspohl</em></a></p><p><strong><em>…is always grateful for a like or follow he can return</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbcb02afc234" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What would Aristotle say about data stories?]]></title>
            <link>https://medium.com/@lverspohl/what-would-aristotle-say-about-data-stories-1-49e97c3ce78d?source=rss-3ed15968ada5------2</link>
            <guid isPermaLink="false">https://medium.com/p/49e97c3ce78d</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-journalism]]></category>
            <category><![CDATA[storytelling]]></category>
            <category><![CDATA[communication]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[lars verspohl]]></dc:creator>
            <pubDate>Sat, 29 Oct 2016 16:01:01 GMT</pubDate>
            <atom:updated>2016-11-08T19:35:28.396Z</atom:updated>
            <content:encoded><![CDATA[<h4>6 principles for better data visualisation #0</h4><p>Over 2000 years ago around the year 350 BC Aristotle wrote <em>Poetics</em>. Unassuming in length, it laid down the 6 principles of one of the most powerful vessels of communication: stories. To be precise: stories as acted out in Greek tragedy (assumed superior to its contemporaries the comedy and the musical play). Stories have of course been around for significantly longer, used to entertain as well as share and memorise knowledge before writing came along.</p><p>In that it shares something with another discipline that originated from similar depths of time and potentially — who knows — was directly connected to storytelling: map making. The first map found dates back to <a href="https://en.wikipedia.org/wiki/History_of_cartography#Earliest_known_maps">16500 BC</a>. It shows the 3 bright stars Vega, Deneb and Altair and not having convened with an attendee, I bet the map maker had a story to tell about their map. Connected or not, he or she planted the seed of something people would call data visualisation some future day.</p><p>Both crafts evolved over time at different pace and rather independently from each other until they were brought into the same sphere — mainly out of necessity as visualisers and storytellers looked around for more effective ways to unfold. But it didn’t quite fit. Stories in the original sense were used for all sorts of communication, but often of the fictional kind, used to convey emotions. Data visualisation often didn’t want to be fictional or emotional. First and foremost it wanted to purvey clean and abstract data, facts, the truth. Furthermore, data visualisation sometimes wanted to show a lot at once, not a linear story, but rather a context: a network of information rather than a straight line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3E2qbXyEc6eav69udKmRxQ.png" /><figcaption>The 2 meaningful animals next to each other</figcaption></figure><p>There is continued talk about potential connections between data visualisation and story. Some say it’s all fine and the two belong together, at least in what one would call <em>explanatory visualisations</em>. Some even allow them to mingle in less constrained <em>exploratory visualisations</em>. Others fear a bad influence of stories on the purity of visual data display and strive to find different friends for it.</p><p>Describing their relation, many well meaning and intelligent people defined stories in the context of data visualisation, and left it there. I want to add a slightly different (but at least well meaning) attempt, by going back to <strong>Aristotle’s grand principles</strong>, the first consistent definition of story, and assemble a storytelling tool-belt for data visualisation.</p><p>No idea if that’ll work… but it might be rewarding, as Aristotle’s principles are by far the most battle-tested; consciously laid out for eternity and flexible in their high level of abstraction. They are simple, pure and universal. But you still may ask: why compare Aristotelian drama with data visualisation? Apples != pears?</p><p>Not quite. Theatre, even aeon-old Greek Tragedy, and data visualisation share a key foundation: they are both communication media. They’re apple and pear on the presentational layer but not on the conceptual. Both are intermediaries between message producers like writers, directors, artists (encoding information) and message receivers like readers, listeners, audiences in general (decoding information). The inscribed purpose of communication is always a changed consciousness in the form of knowledge, belief, opinion or perspective and to achieve this, both producers and receivers, play an active role. And they often use stories to en- or decode information.</p><p>In fictional media like film and theatre stories are used more consistently and consequently than in factual media like scientific journals or, well, data visualisation. But stories are tempting for all communication as they are such an efficient vessel of meaning.</p><p><strong>Streamlined</strong> to the way we make sense of the world,</p><p>suitably <strong>flexible</strong> to live in different contexts,</p><p><strong>dense</strong> enough to be stored as a single unit, yet appropriately</p><p><strong>unspecific </strong>to be filled with the audience’s own world knowledge.</p><p>The presentation layer as well as the techniques to unfold a story might differ from books (thought and action) to films or theatre (visual likeness and similarity), to articles (anecdotes and sidebars) and eventually to data visualisation (graphical primitives and multimedia). But all follow principles of storytelling in some respect in order to unfold a changed perspective.</p><p>But even if the message producers, the ‘media’ didn’t put any effort into laying out stories, the message readers, the ‘audience’ probably would. As Doctor Who once put it: <em>“we’re all stories”</em>. As such they’re hard to escape…</p><p>Well then. Assuming visualisation is communication trying to change meaning and stories are helpful vessels for meaning — let’s look at the universal principles of storytelling Aristotle conjured up for us and see if they can help us produce better data displays. Let’s go through them one after the other, starting with the most central but for our mission most challenging principle: <strong>Plot</strong>.</p><p>Next post, next week, same time, same place…</p><p><em>lars verspohl </em><a href="http://www.datamake.io/"><em>www.datamake.io</em></a><em> @lars_vers </em><a href="https://www.linkedin.com/in/larsverspohl"><em>https://www.linkedin.com/in/larsverspohl</em></a></p><p><strong><em>…is always grateful for a like or follow he can return</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49e97c3ce78d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>