<?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 Andrew McNutt on Medium]]></title>
        <description><![CDATA[Stories by Andrew McNutt on Medium]]></description>
        <link>https://medium.com/@mcnutt?source=rss-410e9ab5a21e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*L4DxPdseTa120-WBnUlE6Q.jpeg</url>
            <title>Stories by Andrew McNutt on Medium</title>
            <link>https://medium.com/@mcnutt?source=rss-410e9ab5a21e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 06:30:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mcnutt/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[Getting your CHI diff ready]]></title>
            <link>https://medium.com/@mcnutt/getting-your-chi-diff-ready-1714eb3c75f6?source=rss-410e9ab5a21e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1714eb3c75f6</guid>
            <category><![CDATA[academic-writing]]></category>
            <category><![CDATA[sigchi]]></category>
            <category><![CDATA[latex]]></category>
            <dc:creator><![CDATA[Andrew McNutt]]></dc:creator>
            <pubDate>Sat, 11 Nov 2023 01:23:36 GMT</pubDate>
            <atom:updated>2023-11-13T21:49:41.481Z</atom:updated>
            <content:encoded><![CDATA[<p>Or how to make red-line diffing your latex-based paper less awful</p><p>It’s CHI revision season again. In North America the leaves are changing from green to red, and so too will our CHI paper drafts become decorated with detritus of red-line edits made to appease our reviewers. CHI, and many other venues, are starting to require/strongly suggest that you provide a PDF highlighting what changes were made in the course of your revision. There are hard ways to this (such as adding \revision{} commands around all of your changes, placing a large burden on you) and easy ways. This blog post is a very brief sketch of how to make it less annoying to produce a diff of latex files automatically.</p><p><strong><em>Step 0.</em></strong> Have latex installed on your local machine</p><p><strong><em>Step 1.</em> Create a snapshot of the source files for your paper at submission time/before revision.</strong> I am lucky that one of my institutions provides me a free OverLeaf pro account, so I can simply go to the appropriate change in the history, and click “download this version” under the hamburger menu. If you happen to be using a version control system for your submission, congrats! I am jealous of you. Anyway.</p><p><em>Create a folder on your computer to support building this diff. Store this snapshot as “old”. (If this is a zip unpack it to be just a folder.)</em></p><p><strong><em>Step 2. </em>Create a snapshot of your source files after you have finished your revision. </strong>Same move, but post edits. <em>Save that as a sibling to the “old” from our previous step, call it “new”.</em></p><p><strong><em>Step 3. </em>Make both snapshots into a single file. </strong>Here you just use the magic of latexpand (executed via command line)</p><pre>mkdir diff-prep<br>latexpand --empty-comments old/chi2024.tex &gt; ./diff-prep/old.tex <br>latexpand --empty-comments new/chi2024.tex &gt; ./diff-prep/new.tex</pre><p>Notice that this strips out the comments! This a good and powerful thing imo.</p><p><strong><em>Step 4. </em>Diff ‘em. </strong>Here we use latexdiff.</p><pre>latexdiff --exclude-textcmd=section,subsection,cmidrule,cmidrulewidth <br>          --exclude-safecmd=cmidrule,cmidrulewidth <br>          --disable-auto-mbox <br>          --graphics-markup=1 <br>           diff-prep/old.tex diff-prep/new.tex &gt; diff.tex</pre><p>There are other latex diff tools, but this one works good for me. I inherited this wall of CLI flags, and I don’t really know/care what they do because they reliably produce the diffs I want. I am aware that this tools is not perfect (for instance it gets very confused by images sometimes), but the document you are preparing is meant to be a communicative guide for your reviewers rather than something publishable (so don’t worry too too much about it).</p><p>(Edit: Since publishing this post<a href="https://fredhohman.com/"> Fred Hohman</a> informed me that you can skip step three by adding a--flatten command to latexdiff)</p><p><strong><em>Step 5. </em>Render the diff. </strong>This can be as easy as just rendering diff.tex in your usual way (for instance I use the Latex Workshop VSCode extension, but TexShop or whatever will do fine). However, sometimes you need to do some surgery to your snapshots or the diff to make this go. You’ll get an output that looks something like:</p><figure><img alt="A chunk of text that reads. Several sections of it have wavy blue underlines indicating that they have been added, while others have red strike throughs indicating that they have been removed." src="https://cdn-images-1.medium.com/max/1024/1*dE4taoxfLVc8PXYqLcmTvA.png" /><figcaption>An example of latexdiff on a CHI2023 paper</figcaption></figure><p>The biggest change I find myself doing is related to moving my figures to a single place that each .tex can see, ( such as a top-level figures/ directory that is sibling to the old and new snapshots we just made. In addition, if you use a lot of conditional logic, you may find it’s a little more fiddly and you may have to touch up the diff before it can render.</p><p>I end up stringing each of these commands together into a little bash script. That way—as I inevitably catch yet-another-typo — it’s simple to regenerate the diff. I end up using a similar approach for getting the arxiv submission ready as well (who needs to see me losing my mind trying to phrase something right in my comments).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1714eb3c75f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Surfacing Visualization Mirages]]></title>
            <link>https://medium.com/multiple-views-visualization-research-explained/surfacing-visualization-mirages-8d39e547e38c?source=rss-410e9ab5a21e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d39e547e38c</guid>
            <category><![CDATA[charts]]></category>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[mirage]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[visual-analysis]]></category>
            <dc:creator><![CDATA[Andrew McNutt]]></dc:creator>
            <pubDate>Thu, 20 Aug 2020 16:45:03 GMT</pubDate>
            <atom:updated>2020-08-20T16:45:03.222Z</atom:updated>
            <content:encoded><![CDATA[<p><em>When reading a visualization is what we see really what we get?</em></p><p><em>This post summarizes and accompanies our paper “</em><a href="https://arxiv.org/abs/2001.02316"><em>Surfacing Visualization Mirages</em></a><em>” that was presented at </em><a href="https://chi2020.acm.org/"><em>CHI 2020</em></a><em> with a best paper honorable mention. This post was written collaboratively by </em><a href="https://www.mcnutt.in/"><em>Andrew McNutt</em></a><em>, </em><a href="http://people.cs.uchicago.edu/~glk/"><em>Gordon Kindlmann</em></a><em>, and </em><a href="https://correll.io/"><em>Michael Correll</em></a><em>.</em></p><h3>TL;DR</h3><p>When reading a visualization, is what we see really what we get? There are a lot of ways that visualizations can mislead us, such that they appear to show us something interesting that disappears on closer inspection. Such <strong><em>visualization mirages</em></strong> can lead us to see patterns or draw conclusions that don’t exist in our data. We analyze these quarrelsome entities and provide a testing strategy for dispelling them.</p><h3>Intro</h3><p>The trained data visualization eye notices red flags that indicate that something misleading is going on. Dual axes that don’t quite match up. Misleading color ramps. Dubious sources. While learning how visualizations mislead is every bit as important as learning how they are created, even the studious can be deceived!</p><p>These dastardly deceptions need not be deviously devised either. While some visualizations are of course created by <a href="https://idl.cs.washington.edu/files/2017-BlackHatVis-DECISIVe.pdf">bad actors</a>, most are not. Even designs crafted with the best of intentions yield all kinds of confusions and mistakes. An uncareful or careless analyst might hallucinate meaning where there isn’t any or jump to a conclusion that is only hazily supported.</p><p>What can we say about the humble bar chart below on the left? It appears that location B has about 50% more sales than location A. Is the store in location A underperforming? Given the magnitude of the difference, I’d bet your knee jerk answer would be yes.</p><figure><img alt="A bar chart is revealed to be possibly made of a series of wildly different input datasets" src="https://cdn-images-1.medium.com/max/865/1*ZKM_YJFW2bTM0aw08bL-aA.png" /></figure><p><a href="https://www.autodeskresearch.com/publications/samestats">Many patterns can hide behind aggregated data</a>. For example, a simple average might hide dirty data, irregular population sizes, or a whole host of other problems. Simple aggregations like our humble bar chart are the foundation of many analytics tools, with subsequent analyses often being built on top of these potentially shaky grounds.</p><p>What are we to do about these problems? Should we stop analyzing data visually? Throw out our computers? Perhaps we can form a theory that will help us build a method for automatically surfacing and catching these quarrelsome errors?</p><figure><img alt="A flow chart describing the visual analytics process." src="https://cdn-images-1.medium.com/max/1024/0*0xfi1IRYXxvNAxnB" /><figcaption>The chart-making process is full of moments of agency for the chart creator. What counts as data? What is an appropriate way to manipulate that data? How do I show this data? How do I go about understanding it? The answers to all of these questions can affect the readers ultimate takeaways.</figcaption></figure><h3>Enter Mirages</h3><p>On the road to making a chart or visualization there are many steps and stages, each of which are liable to let error in. Consider a simplified model: an analyst decides how to curate data, how to wrangle it into a usable form, how to visually encode that data, and then finally actually how to read it. When the analyst makes a decision, they exercise agency and create an opportunity for error, which can cascade along this pipeline, creating illusory insights.</p><p>Something as innocuous as defining the bins of a<a href="https://medium.com/@mcorrell/looks-good-to-me-visualizations-as-sanity-checks-6fd1ffa37ab9"> histogram can mask underlying data quality issues</a>, which might in turn lead to incorrect inferences about a trend. Arbitrary choices about axis ordering in a radar chart can cause a reader to falsely believe one job candidate is good while another is lacking. Decisions about what type of <a href="https://whitecollar.thenewinquiry.com/">crime actually counts as a crime</a> can lead to maps that drive radically different impressions about the role of crime in a particular area.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*cJH5xoOCQ_9YRK3ISMdlvg.png" /><figcaption>While charts tend to feel trust worthy, the harmless-seeming choices that create them can cause all sorts of hallucinations.</figcaption></figure><p>The first step in addressing a problem is often to name it, so we introduce a term for these errors: Visualization Mirages. We define them as</p><blockquote>“<em>any visualization where the cursory reading of the visualization would appear to support a particular message arising from the data, but where a closer re-examination would remove or cast significant doubt on this support.</em>”</blockquote><p>Mirages arise throughout visual analytics. They occur as the result of choices made about data. They come from design choices. They depend on what you are trying to do with the visualization. What may be misleading in the context of one task may not interfere with another. For instance, a poorly selected aspect ratio could produce a mirage for a viewer who wanted to know about the correlation in a scatterplot, but is unlikely to affect someone who just wants to find the biggest value.</p><figure><img alt="A man crawls across a desert following a a sign labeled “VA process” towards a mirage that is labeled “insights”" src="https://cdn-images-1.medium.com/max/600/0*t2A0LwLY-jKJQQ2q" /><figcaption>We all thirst for insight in visual analytics (or anywhere else). This desire can cause us to overlook important details or forget best practices.</figcaption></figure><p>The errors that create mirages have both familiar and unfamiliar names: <a href="http://dorisjunglinlee.com/files/Vispilot_IUI_CameraReady.pdf">Drill-down Bias</a>, <a href="http://mimionuoha.com/the-library-of-missing-datasets">Forgotten Population or Missing Dataset</a>, Cherry Picking, <a href="https://en.wikipedia.org/wiki/Modifiable_areal_unit_problem">Modifiable Areal Unit Problem</a>, <a href="https://idl.cs.washington.edu/files/2017-BlackHatVis-DECISIVe.pdf">Non-sequitur Visualizations</a>, and so many more. An annotated and expanded version of this list is included in the paper <a href="https://arxiv.org/pdf/2001.02316.pdf">supplement</a>. There is a sprawling universe of subtle and tricky ways that mirages can arise.</p><p>To make matters worse, there are few automated tools to help the reader or chart creator know that they haven’t deceived themselves in pursuit of insight.</p><h3>Do these things really happen?</h3><p>Imagine you are curious about the trend of global energy usage over time. A natural way to address these questions would be to fire up Tableau and drop in the <a href="https://datacatalog.worldbank.org/dataset/world-development-indicators">World Indicators dataset</a>, which consists of vital world statistics from 2000 to 2012. The trend over time (a) shows that there was a sharp decrease in 2012! This would be great news for the environment, were it not illusory, as we see in (b) when checking the set of missing records.</p><figure><img alt="A line chart with the caption energy down? A bar chart with the caption Count of Nulls. A line chart with energy up?" src="https://cdn-images-1.medium.com/max/748/0*xAtyOdavvhfxquAy" /></figure><p>If we try to quash these data problems by switching the aggregation in our line chart from SUM to MEAN, we find that the opposite is true!! There was a sharp increase in 2012. Unfortunately this conclusion is another mirage. The only non-null entries for 2012 are <a href="https://en.wikipedia.org/wiki/OECD">OECD</a> countries. These countries have much higher energy usage than other countries across all years (d).</p><figure><img alt="Two line charts. Left one shows Energy Usage vs Life Expectancy over time, the right one show energy use over time" src="https://cdn-images-1.medium.com/max/1024/0*8mQWbNq_zYbnMP4w" /></figure><p>Given these irregularities we can try removing 2012 from the data, and focus on the gradual upward trend in energy usage in the rest of the data. As we can see on the left, it appears that energy usage is tightly correlated with average life expectancy, perhaps more power means a happier life for everyone after all. Unfortunately this too is a mirage. The y-axis of this chart has been altered to make the trends appear similar, and obscures the fact that energy use is flat for most countries.</p><p>Now of course, you’re probably saying:</p><h3>But I’m really smart, I wouldn’t make this type of mistake</h3><p>That’s great! Congrats on being smart. Unfortunately, even those with high data visualization literacy make mistakes. <a href="http://users.eecs.northwestern.edu/~jhullman/vis_rhetoric.pdf">Visualizations are rhetorical devices </a>that are easy to trust too deeply. Charting systems often give an air of credibility that they don’t necessarily warrant. It is often easier to trust your initial inferences and move on. Interactive visualizations with exploratory tools that help to might dispel a mirage <a href="https://hal.inria.fr/hal-01133595/document">are often only glanced at by casual readers</a>. Sometimes you are just tired and miss something “obvious”.</p><figure><img alt="A chart showing the gun deaths in florida over time" src="https://cdn-images-1.medium.com/max/320/0*Mm6DHe_UUQvnyl3d.jpg" /><figcaption>This infamous chart appears on first glance to be saying that ‘Stand Your Ground’ decreased gun deaths, but on closer inspection it shows the opposite! Terrifying! (The author of this chart wasn’t actually trying to confuse anyone, they were just trying to explore a new design language)</figcaption></figure><p>Some visualization problems are easy to detect, such as axes pointed in an un-intuitive or unconventional direction or a pie chart with more than a handful of wedges. This type of best practice knowledge isn’t always available, for instance, what if you are trying to use a novel type of visualization? (A <a href="https://xeno.graphics/">xenographic</a> perhaps?) There’d be nothing beyond your intuition to help guide you.</p><p>Other, more terrifying, problems only arise for particular datasets when paired with particular charts. To address these we introduce a testing strategy (derived from <a href="https://en.wikipedia.org/wiki/Metamorphic_testing">Metamorphic Testing</a>) that can identify some of this thorny class of errors, such as the aggregation masking unreliable inputs that we saw earlier with our humble bar chart.</p><p>Testing for errors is easy if you know the correct behavior of a system. Simply inspect the system and report your findings. In errors in the hinterlands of data and encoding we are left without such a compass. Instead, we try to find guidance by identifying symmetries across data changes.</p><p>The order in which you draw the dots in a scatterplot shouldn’t matter, right? Yet, depending on the dataset, it often can!!! This can erase data classes or cause false inferences. We test for this property by shuffling the order of the input data and then comparing the pixel-wise difference between the two images. If the difference is above a certain threshold we know that there may be a problem. This is the essence of our technique: for a particular dataset, execute a change that should have a predictable result (here no change), and compare the results.</p><figure><img alt="A series of 3 scatterplots. The first two show the same data but appear different. The third image highlights the differences" src="https://cdn-images-1.medium.com/max/1024/0*eBhutFqFKUGKWbKW" /><figcaption>A simple scatterplot can hide the distributions it displays through draw order. This problem won’t affect every dataset, but here it hides the prevalence of the Americas in the middle of the distribution.</figcaption></figure><p>While it’s still in early development, we find that this approach can effectively catch a wide variety of visualization errors that fall in this intersection of matching encoding to data. These techniques can help surface errors in over-plotting, aggregation, missing aggregation, and a variety of other contexts. It remains an open challenge on how to effectively compute these errors (as their computation can be burdensome) as well as how to best describe these errors to the user.</p><h3>Where does that leave us?</h3><p>Visualizations, and the people who create them, are prone to failure in subtle and difficult ways. We believe that visual analytics systems should do more to protect their users from themselves. One way these systems can do this is to surface visualization mirages to their users as part of the analytics process, which, hopefully will guide them towards safer and more effective analyses. Applying our metamorphic testing for visualization approach is just one tool in the visualization validation toolbox. The right interfaces to accomplish this goal is still unknown, although applying a metaphor of software <a href="https://www.mcnutt.in/assets/McNutt_Kindlmann_2018.pdf">linting seems</a> <a href="https://research.tableau.com/paper/visualint-sketchy-situ-annotations-chart-construction-errors">promising</a>. For more details check out <a href="https://arxiv.org/pdf/2001.02316.pdf">our paper</a>, take a look at the <a href="https://github.com/tableau/Visualization-Linting">code repo</a> for the project, or watch our <a href="https://www.youtube.com/watch?v=arHbVFbq-mQ">CHI talk</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d39e547e38c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/multiple-views-visualization-research-explained/surfacing-visualization-mirages-8d39e547e38c">Surfacing Visualization Mirages</a> was originally published in <a href="https://medium.com/multiple-views-visualization-research-explained">Multiple Views: Visualization Research Explained</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Brief Saga Concerning the Making of a Tarot Deck About the American Highway System]]></title>
            <link>https://medium.com/@mcnutt/a-brief-saga-concerning-the-making-of-a-tarot-deck-about-the-american-highway-system-2eaebf3320c8?source=rss-410e9ab5a21e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2eaebf3320c8</guid>
            <category><![CDATA[sketch]]></category>
            <category><![CDATA[tarot]]></category>
            <category><![CDATA[art]]></category>
            <dc:creator><![CDATA[Andrew McNutt]]></dc:creator>
            <pubDate>Mon, 10 Dec 2018 20:52:30 GMT</pubDate>
            <atom:updated>2018-12-10T20:52:30.765Z</atom:updated>
            <content:encoded><![CDATA[<p>A little essay</p><p>In the winter of December 2015– 2016 I yearned to make something great. I had recently changed jobs from a little tech company to a large tech company, and I found myself feeling small. There were lots of amazing people all around me, executing high speed acts of incredible technological derring-do. I wanted to both prove that I was great and that I was different than the average cog in the wheel of the panopticon of convenience. Though, it is perhaps hard to say if I actually am or was, because I suspect that’s how everyone feels. Regardless, I set off to set myself apart from other engineers and tech workers by making something intricate yet technical, something quirky and literary: a tarot deck.</p><p>Tarot, for the uninitiated, is a system of divination that spans back hundreds of years. It has had many many variations in its time, but the form that it has converged on typically consists of seventy eight cards:</p><ul><li><strong><em>Fifty Six</em></strong>: Four suits of fourteen cards a piece known as the minor arcana. They can be further divided into the number cards, one through ten, and the named cards, sometimes called the court. The suits that are involved typically vary deck to deck, but most follow that of the most famous deck, the Rider-Waite, which uses a quartet consisting of Coins, Wands, Swords, and Cups.</li><li><strong><em>Twenty two</em></strong>: When tarot are seen in popular media, it is often a member of this collection, the major arcana, which are displayed. These cards have evocative names like “The Fool”, “The Sun”, or “Death”. (According to wikipedia the fool is different than the rest of the major arcana, though it’s a little beyond me why/how.)</li></ul><p>Divination using tarot usually takes the form of a tarot reading, in which the reader draws a number of cards in a particular layout and divines the future foretold therein. The specific details of this process are interesting, but they aren’t really the focus of this article.</p><p>Now, I wish I could tell you that this article was the regal announcement of something wonderful that I had made: something splendid and good that you could hold in your hands. Unfortunately, this is not that kind of article. Instead it is a retrospective on something that I wanted to be great and the way it fell short. It is a simple story, and may be just a little longer than you were hoping, but <em>this is the only light that will ever shine on this project, so I want to shine it as long as I can</em>.</p><p>Before we get into all that, let’s skip to the end and look at some of the results. Because thankfully, it wasn’t all for nothing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f8hcZSr6OH_D-uMBCj9XXQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e2kxKUMkkn9VWpJuljCDNw.png" /></figure><h3>THE THEME</h3><p>Like many Americans, I love the highway. There is something amazing and comforting about the mixture of extreme variety of the ever changing countryside and the extreme sameness of the thing allowing us to move through those spaces. It is stilted at this late date to celebrate the mechanistically reproduced micro societies that adorn every so many miles of freeway, but i don’t care. Good lord, do I love the comfort of seeing the yellow scalloped logo of a Shell gas station rise steadily over the horizon after too long bending through vast distances. I love the regular-ness of knowing how many miles away an exit is based on its number, I love the simple brilliance of the numbering scheme that demarks a highway as north-south vs west-east. And importantly: I adore the direct and understandable signage that shines a light through a tangled web of roads criss-crossing this vast country.</p><p>You might even say that there is a certain magic that this all possesses.</p><p>My tarot deck, is one that tries to capture that magic. Tarot is a thing of signs and symbols, some decks are deeply riddled and enshrouded with elaborate meaning. I wanted to make a deck that held meaning in an interesting way but took a, perhaps, clearer route on its voyage with provenance.</p><h3>THE BEGINNING</h3><p>I am not a magical person. I am the grandson of a physicist, the child of skeptical modernist architects, a studier of physics and computer science. There is nothing about me that should lead to a pursuit of the mystical. However, when the muse calls, you listen. So I tried to make up for what I lacked in magic with diligent and attentive study. As you might expect, there is a vast body of literature on the internet to help guide and channel a nascent tarot designer, so I dug in.</p><p>Working, as I was through the course of this project, as a software engineer focused on data visualization and user interfaces, I had been developing a toolset for designing things and I diligently applied it here. I began typographically: I assembled a pallet of the official colors of the US highway system, and got a hold of the official font, the amazingly named Highway Gothic. (You can find it too, it’s not hard to find, it’s just not mine to give.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*qSudVo3TMvyh5riP59y0pw.png" /><figcaption>The official palette for the us highway system</figcaption></figure><p>I had been working a lot in Sketch, a program that is like illustrator for web development, and so I picked it as my design tool. After some initial sketching on paper I set off to work. I built modularly one section of the deck at a time, first the major arcana, then the numbered minor arcana, and the court. While I working on the major arcana I found myself in Mexico in a tourist resort town trying desperately to build a product for work over the new year. One memorable moment found me working on my tarot deck in an outdoor cafe near the edge of the jungle, when a dog suddenly fell through the ceiling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4VH1YRl5qFOtA1f3xC1oHQ.png" /><figcaption>A sample of the major arcana portion of the deck</figcaption></figure><p>I decided to base my symbology on a mix between the common Rider-Waite and Aleister Crowley’s Thoth tarot deck. I kept the legends on all of the cards like the Thoth, but bent more towards Rider-Waites visual themes and suit naming. Following on my chosen theme, I tried to make each card pictographic and symbolic, like it wouldn’t be out of place on a surreal exit sign (three miles down a magician is screwing something up). I found myself riding my motorcycle up and down the San Francisco Peninsula when I was stuck, often through the same stretches in Santa Cruz county again and again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r2IfQNZ5X6yhD9Qs_ocHqA.png" /><figcaption>A sample of the numbered minor arcana. This deck has four suits: coins, swords, cups, and wands.</figcaption></figure><p>Things were going well. I seemed to find a voice that met with my goal and I was progressing as an artist. Of course, not every image turned out well (especially the whole suit of wands, jeez, I did not address those design problems very creatively), but as a whole it mostly worked. I got to the end and the whole court fell out of my head in about a week. It felt like I really knew what I was doing, like my plans had really clicked into place. I was happy that I had developed a repeating set of symbols, a collection of characters who would show up in different places throughout the deck (such as the woman with a hand for a face, what’s she up to in her various doings).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vYhF28acrsR5bPqG7SykiQ.png" /><figcaption>The complete court from the deck. Most of the names for these cards were invented, as opposed to many of the names of the other minor aracana which were copied from the Thoth deck.</figcaption></figure><h3>A SHOT AT THE END</h3><p>By June of 2016 I had a version of the deck. Sure there were still lots of little tweaks to obsess over, but the thing finally had a form. The end goal for this project was to make a kickstarter, not for the purpose of getting money, just for the purpose of making there be lots of copies of the deck out there in the world. An unpopular adage from around that time was that Millennials all get one kickstarter, more than that and you are just a burden on your friends. Other folks I know used that shot to go on road trips with far away romantic partners, or pay for an expensive career training. (This was a little bit before kickstarter etc was America’s main health care platform). I was ready to make to this niche art project my one shot. Or least I thought was. I started getting ready to get a demo copy from a press and I found that I needed to face some unpleasant facts.</p><p>First and foremost, the deck didn’t have a name. Tarot decks typically have names that are mystical and inspiring, like the PixelSpiritDeck and Slow Holler. But, being the non-magical person I described above, I couldn’t think of anything. I was at a loss. My then partner pointed out that a tarot deck without an interpretation guide (a book that tells the reader how to understand the tarot) is worthless to most people. I was stuck.</p><p>I tried out lots of names: the tarot of the parkway, the highway ghost deck, the Eisenhower, etc. I watched other Kickstarter Tarot artists videos, thought deeply, and hung out near the buffalo in golden gate park. I ended up with the Jacobs-Moses tarot, after Jane Jacobs and Robert Moses. A tarot deck built in the spirit of conflict between home and industry, of well spoken and focused titans; it sounds like a fine idea, yet it didn’t match the thing that I made. I got a test copy from the printers with this branding, and everything looked good, but didn’t feel right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UWBc6XPhMLNUXw3co87WkA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oMOWj1Pc1O39WRZd9csOAA.jpeg" /><figcaption>The box for the one test print of the deck. In hindsight I really wish the deck I made had followed this theme. Too late.</figcaption></figure><p>I became paralyzed, I wanted to move forward, to write the kickstarter. But I found that I couldn’t, I couldn’t bring myself to do a bad job, and I couldn’t get the work done. I carried around this ball of anxiety that I didn’t know what to do with. By and by this feeling faded, work heated up in new and surprising ways, I got distracted with applying for graduate school, and the deck got swept under the rug, forgotten mostly.</p><h3>WHERE DO WE STAND</h3><p>When do we let projects die? I care deeply about the things I make; sometimes when I am deep in a project its name rattles around my mind, held so closely to my waking thought that it exists throughout my being, I almost breathe its name. This tarot deck was no different, I loved it and carried it with me, despite its lack of name. I was eager to show it off and get feedback, it was what I had going on during that winter and spring. Yet due to time and circumstance it fell by the wayside, it became forgotten. Every once in a while I’d remember it and feel bad that I didn’t finish it.</p><p>I now cut this thread. With the release of this write up, I am definitively giving up on this project. No longer will it idle in the back of my mind, humming with quiet possibility, burdening my future. Instead I release it and all assets associated with it under the MIT License. Do whatever you want with it. I have included in the associated Github repository (see bottom) a printable version, though you may have to do some cutting to make it look right. I also include the SVG assets (along with the sketch files for generating them), so that you may slice dice, remix and rediscover as you wish.</p><p>The version of the deck that I present to you is mostly preserved in just the way it was when the project reached its little end, with one exception. Before releasing the deck I made a single change, and I’m sure you’ll forgive me. When I started making this deck, the political environment had a much brighter look than it does today, and so I felt comfortable satirizing a nickname of a then rising republican presidential candidate. Assuming, naively, that his candidacy would be a silly footnote in the twenty teens section of American history, right next to our various dank memes and the quickly forgotten silliness of yo. Alas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*eLEyv3_25okTnWpCgg4JjA.png" /></figure><p>Sometimes art changes when you aren’t touching it: I needed to update that card in light of the horrors of the Trump administration.</p><h3>THE REAL END</h3><p>This tarot deck was the first really large scale project I carried out entirely by myself. It involved learning a lot of different ideas and technologies. While it was mostly a great experience, in the end: it failed. It failed because I didn’t understand the premise well enough to do the hard creative lifting that would have allowed me to finish. It failed because, while I was the person that made it, I don’t know if I was the right person to have made it. The lesson, for me, is that while good engineering and diligence can carry you a long way, the thing that helps you cross the finish line is a kind of magic unto itself.</p><p>I have heard rock guitarist turned philosopher of craft, Robert Fripp, say that in closing creative efforts there are stops, ends, and completions, ordered for the completeness of the work when it is abandoned. This project came to a quiet stop, which has been profoundly dissatisfying to me. I present this article to you now, so that the project, in spite of its failure, might be complete.</p><h4>Links</h4><p>You can find the Github for the project, which includes all of the assets under the MIT license at <a href="https://github.com/mcnuttandrew/tarot-deck">https://github.com/mcnuttandrew/tarot-deck</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2eaebf3320c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Visualization with react-vis]]></title>
            <link>https://medium.com/data-science/advanced-visualization-with-react-vis-efc5c6667b4?source=rss-410e9ab5a21e------2</link>
            <guid isPermaLink="false">https://medium.com/p/efc5c6667b4</guid>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[react-vis]]></category>
            <dc:creator><![CDATA[Andrew McNutt]]></dc:creator>
            <pubDate>Mon, 21 May 2018 16:31:35 GMT</pubDate>
            <atom:updated>2018-05-21T16:31:35.369Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using Voronois, single pass rendering, and canvas components for amazing user experiences</h4><p>So you’ve started to do some data visualization with <a href="https://github.com/uber/react-vis">react-vis</a>, you’ve built some charts of your own, maybe you’ve read <a href="https://medium.com/u/792d0122c5bb">Shyianovska Nataliia</a> ‘s wonderful introduction <a href="https://medium.com/dailyjs/data-visualization-with-react-vis-bd2587fe1660">Data Visualization with react-vis</a>, or perhaps even built a <a href="http://www.jeromecukier.net/?p=1700">dashboard</a>. It’s time to learn some techniques for handling larger sizes of data and to handle more complex UI interactions. In the course of this article we will see how to use single pass rendering, canvas components, debounced state updates, and Voronois. Buckle in, it’s gonna be a wild ride!</p><p>To get started you can set up scaffold a new app using <a href="https://www.npmjs.com/package/create-react-app">create-react-app</a>, and then run in the terminal</p><pre>npm install react-vis --save<br># we will also be using a few additional libraries <br># so install these too<br>npm install --save d3-fetch d3-scale d3-scale-chromatic debounce simplify-js</pre><p>That said, I use a slightly different configuration for my apps, which you can <a href="https://github.com/mcnuttandrew/advanced-react-vis-tutorial">check out here (along with the code for this whole article).</a></p><h4>Getting and preparing the data</h4><p>A traditional technique for learning how to do anything is to imitate the masters, and this article will be no exception. We will be exploring New York Times’s 2016 visualization “Stephan Curry’s 3 Point Record in Context”.</p><p><a href="https://www.nytimes.com/interactive/2016/04/16/upshot/stephen-curry-golden-state-warriors-3-pointers.html">Stephen Curry&#39;s 3-Point Record in Context: Off the Charts</a></p><p>There’s a lot going on in this visualization! Each line shows the number of three pointers made by a particular player over the course of a particular season. This information is made accessible by a dynamic mouseover which simultaneously highlights that particular player-year and provides a tooltip which describes exactly which line the user is hovering over.</p><p>Our first step will be to acquire the data. Pleasantly, NYT serves it’s data for this article in CSV’s so we can pretty easily grab that by watching the network tab in chrome, as below. Once you’ve downloaded the data file, place it somewhere within your application, I put it under a folder called data and named it “nyt-rip.csv”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rjOyrSh7yw0NNecQgLWCOg.gif" /><figcaption>Capturing the CSV data that we will be using for our visualization by watching the network tab on Chrome. Refreshing the page triggers a lot of network calls, we then filter the network history to only CSV’s, and save the relevant file by double clicking it.</figcaption></figure><p>The format of this csv is a little inconvenient, it has columns for a player id, the players name, the year, and then the number of three throws for each game of the season. Let’s clean this up into a format thats a little easier to work with:</p><pre>const nonNumericRows = {<br>  player: true,<br>  pname: true,<br>  year: true<br>};</pre><pre>// reformats input csv so that each row <br>// has details about the corresponding player<br>// and an array of points describing that players record<br>export function cleanData(data) {<br>  return data.map(row =&gt; {<br>    // extract all of the columns for <br>    // this row that update that players score<br>    const gameData = Object.keys(row)<br>      .filter(key =&gt; !nonNumericRows[key] &amp;&amp; row[key] !== &#39;NA&#39;)<br>      .map((key, x) =&gt; ({x, y: Number(row[key])}));</pre><pre>    // return a formatted object to manipulate<br>    return {<br>      player: row.player,<br>      pname: row.pname,<br>      year: row.year,<br>      height: gameData[gameData.length - 1],<br>      gameData<br>    };<br>  });<br>}</pre><p>Excellent, now we have a mechanism to format our data in a usable way. While we’re writing utility functions, let’s also write one to grab the data domain:</p><pre>export function getDataDomain(data) {<br>  const {min, max} = data.reduce((acc, player) =&gt; {<br>    return player.gameData.reduce((mem, row) =&gt; {<br>      return {<br>        min: Math.min(mem.min, row.y),<br>        max: Math.max(mem.max, row.y)<br>      };<br>    }, acc);</pre><pre>}, {min: Infinity, max: -Infinity});<br>  return [min, max];<br>}</pre><p>Put both of these functions into a utils.js file, and we’re off to the races.</p><h4>A first naive approach</h4><p>To set the stage for our subsequent optimizations let’s throw together a naive approach. There are 750 player-years rows in our data set, so let’s just have 750 LineSeries. When we hover over them, let’s redraw the lines and highlight the selected one. Pretty reasonable! Here is a full pass at the naive implementation, after which I’ll go through and describe each part:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7df5142203abd15c579f45fdfe9bd1c5/href">https://medium.com/media/7df5142203abd15c579f45fdfe9bd1c5/href</a></iframe><p>Oof thats a lot all at once! But it’s pretty easy to deal with if break it apart in chunks. The first thing our component does when it gets ready to mount is to call out for data via the <a href="https://github.com/d3/d3-fetch#csv">d3-fetch csv</a> function, we then clean the data and save it into the state for ingestion in the near future.</p><pre>componentWillMount() {<br>    csv(&#39;data/nyt-rip.csv&#39;)<br>      .then(data =&gt; this.setState({<br>        data: cleanData(data),<br>        loading: false<br>      }));<br>  }</pre><p>We start our render function by refusing to try to render our component if the data hasn’t been loaded yet, instead just giving back a loading message (though you could easily give show a spinner or use something fancy like <a href="https://github.com/balthazar/placeloader">placeloader</a>). Next we build up a color scale powered by <a href="https://github.com/d3/d3-scale-chromatic">d3-scale-chromatic</a> using our getDataDomain function from the previous section. In this article we are primarily interested in reconstructing the feel (as opposed to the exact look) of the original NYT visualization, so here we use a different color scale, and forgo some of their extra chart decorations.</p><pre>const {loading, highlightSeries, data} = this.state;<br>if (loading) {<br>  return &lt;div&gt;&lt;h1&gt;LOADING&lt;/h1&gt;&lt;/div&gt;;<br>}</pre><pre>const dataDomain = getDataDomain(data);<br>const domainScale = scaleLinear().domain(dataDomain).range([1, 0]);<br>const colorScale = val =&gt; interpolateWarm(domainScale(val));</pre><p>Finally, we come to the actual rendering of our chart. We start by looking over all of our data rows and creating a LineSeries for each of them along with defining a rudimentary interaction technique. Next we add a LabelSeries to highlight only certain points along the yAxis, and the xAxis with special formatting to match the labels given by the NYT graphic.</p><pre>&lt;XYPlot {...layout}&gt;<br>  {data.map((player, idx) =&gt; {<br>    const playerHighlightString = `${player.pname}-${player.year}`;<br>    return (<br>      &lt;LineSeries<br>        key={idx}<br>        strokeWidth=&quot;4&quot;<br>        curve=&quot;curveStepBefore&quot;<br>        data={player.gameData}<br>        onSeriesMouseOver={() =&gt; <br>            this.setState({highlightSeries: playerHighlightString})}<br>        onSeriesMouseOut={() =&gt; <br>            this.setState({highlightSeries: null})}<br>        stroke={<br>          playerHighlightString === highlightSeries ? &#39;black&#39; :<br>           colorScale(player.gameData[player.gameData.length - 1].y)<br>        }<br>        /&gt;);<br>  })}<br>  &lt;LabelSeries<br>    data={data.filter(row =&gt; labelMap[`${row.pname}-${row.year}`])}<br>    style={{fontSize: &#39;10px&#39;, fontFamily: &#39;sans-serif&#39;}}<br>    getY={d =&gt; d.gameData[d.gameData.length - 1].y}<br>    getX={d =&gt; 82}<br>    labelAnchorX=&quot;start&quot;<br>    getLabel={d =&gt; <br>      `${d.pname} - ${d.gameData[d.gameData.length - 1].y}`}/&gt;<br>  &lt;XAxis<br>    style={{ticks: {fontSize: &#39;10px&#39;, fontFamily: &#39;sans-serif&#39;}}}<br>    tickFormat={d =&gt; <br>       !d ? &#39;1st game&#39; : (!(d % 10) ? `${d}th` : &#39;&#39;)}/&gt;<br>&lt;/XYPlot&gt;</pre><p>The astute reader will observe that we’ve used a couple of constants, imported from a separate constants.js file, which are pulled out for logical convience:</p><pre>export const desiredLabels = [<br>  {pname: &#39;Brian Taylor&#39;, year: 1980},<br>  {pname: &#39;Mike Bratz&#39;, year: 1981},<br>  {pname: &#39;Don Buse&#39;, year: 1982},<br>  {pname: &#39;Mike Dunleavy&#39;, year: 1983},<br>  {pname: &#39;Larry Bird&#39;, year: 1986},<br>  {pname: &#39;Danny Ainge&#39;, year: 1988},<br>  {pname: &#39;Michael Adams&#39;, year: 1989},<br>  {pname: &#39;Michael Adams&#39;, year: 1990},<br>  {pname: &#39;Vernon Maxwell&#39;, year: 1991},<br>  {pname: &#39;Vernon Maxwell&#39;, year: 1992},<br>  {pname: &#39;Dan Majerle&#39;, year: 1994},<br>  {pname: &#39;John Starks&#39;, year: 1995},<br>  {pname: &#39;Dennis Scott&#39;, year: 1996},<br>  {pname: &#39;Reggie Miller&#39;, year: 1997},<br>  {pname: &#39;Dee Brown&#39;, year: 1999},<br>  {pname: &#39;Gary Payton&#39;, year: 2000},<br>  {pname: &#39;Antoine Walker&#39;, year: 2001},<br>  {pname: &#39;Jason Richardson&#39;, year: 2008},<br>  {pname: &#39;Stephen Curry&#39;, year: 2013},<br>  {pname: &#39;Stephen Curry&#39;, year: 2014},<br>  {pname: &#39;Stephen Curry&#39;, year: 2015},<br>  {pname: &#39;Stephen Curry&#39;, year: 2016}<br>];</pre><pre>export const layout = {<br>  height: 1000,<br>  width: 800,<br>  margin: {left: 20, right: 200, bottom: 100, top: 20}<br>};</pre><pre>export const NUMBER_OF_GAMES = 82;<br>export const MAX_NUMBER_OF_THREE_POINTERS = 405;</pre><p>Putting it all together, this looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*UmWSUD5Ckowwn7qpFkpPJw.gif" /></figure><p>Pretty cool! However, the responsiveness is not very good, lines don’t highlight when we get close to them, and the browser noticeably appears to lag. This strategy also prevents us from adding the tooltip along the side (while we could it would be subject to a lot of jitter as we hover across various elements). There’s gotta be a better way!</p><h4>A better architecture</h4><p>So far we’ve been rendering our series using SVG lines. While this approach makes it easy to reason about the state of the UI, it is REALLY inefficient to redraw all of our lines every time. This is due to the fact that each of these lines is modeled as a very detailed DOM node, which weighs quite heavily on the browser. To alleviate this weight we can use the built in react-vis canvas series, LineSeriesCanvas. Canvas tends to be quite a lot faster to render than SVG, but doesn’t have the same detailed representation in the DOM, which means that any interactions have to be hand brewed. Evidently, dropping this new series into our naive solution will make the whole page faster, but we will lose our dynamic interactivity.</p><p>To address this we will separate our chart into two components, one that handles interactivity, and one that handles everything else. This is motivated by the idea by the idea that React only executes the render function for components that have been updated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*qiWMKN2emmn-9HozPZlz9w.png" /><figcaption>The organization of our chart component after breaking out the interactive parts into a separate component</figcaption></figure><p>Through this architecture we will have a component that renders the canvas lines, and one that will render the the highlight line and highlight tooltip. Thus effectively separating the elements that will be quick to render from those that will be expensive or time consuming to render. Some psuedo-code for the layout:</p><pre>&lt;div className=&quot;relative&quot;&gt;<br>  &lt;NonInteractiveParts /&gt;<br>  &lt;InteractiveParts /&gt;<br>&lt;/div&gt;</pre><p>We want these components to appear to be a single beautiful chart, so we give the interactive parts css properties</p><pre>position: absolute;<br>top: 0;</pre><p>This allows the interactive parts to “sit on top of” the non-interactive properties, thus completing the look.</p><h4>The static parts</h4><p>We’re really getting somewhere now. Observe that the static parts of the of chart are pretty similar to the what we had in the naive approach; just a container with some series in it. In the interest of brevity we can combine the root component and canvas part illustrated above into a single component, as each of them is only rendered a single time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e14ed5a7a31c0c4f6213c3fab1926d7/href">https://medium.com/media/2e14ed5a7a31c0c4f6213c3fab1926d7/href</a></iframe><p>This new component is quite similar to our first one. Our mounting step does a little extra work to facilitate the rendering of the interactivity component — more on that in a moment— and makes a call to our soon to be becoming InteractiveComponents. But other than that, not much has changed!</p><h4>The interactive part</h4><p>Here comes the cool stuff. We saw above that we prepared our data a little bit extra in the componentWillMount step to get it ready for the interactive component, let’s take a more detailed look:</p><pre>componentWillMount() {<br>    csv(&#39;data/nyt-rip.csv&#39;)<br>      .then(data =&gt; {<br>        const updatedData = cleanData(data);<br>        const playerYearMap = updatedData.reduce((acc, row) =&gt; {<br>          const {pname, year, gameData} = row;<br>          acc[`${pname}-${year}`] = gameData[gameData.length - 1].y;<br>          return acc;<br>        }, {});</pre><pre>        const playerMap = updatedData.reduce((acc, row) =&gt; {<br>          acc[`${row.pname}-${row.year}`] = row;<br>          return acc;<br>        }, {});<br>        this.setState({<br>          data: updatedData,<br>          loading: false,<br>          allPoints: buildVoronoiPoints(updatedData),<br>          playerYearMap,<br>          playerMap<br>        });<br>      });<br>  }</pre><p>Our cleaned data is just the same as before, squeaky and easy to use. Next we introduce a new variable variable called playerYearMap, this is an object with keys equal to the player-year unique identifiers and values equal to the maximum score number of three pointers each player reached. This will be used to simplify the positioning of the labels and the tooltip. Similarly we introduce a playerMap, which also also has player-year identifiers as keys, but this time the whole row as values. This will allow for fast/constant time lookup of rows as we mouse over things.</p><p>The last new variable is called allPoints and is generated by a function called buildVoronoiPoints. What could that be for I wonder? Well here is the function (it lives in utils):</p><pre>export function buildVoronoiPoints(data) {<br>  return data.reduce((acc, {player, pname, year, gameData}) =&gt; {<br>    return acc.concat({<br>      player,<br>      pname,<br>      year,<br>      x: 41,<br>      y: gameData[gameData.length - 1].y<br>    });<br>  }, []);<br>}</pre><p>This creates a single point for each player in the center of the of the domain at the “height” of that players maximum number of three pointers. We can use this to create a Voronoi. A Voronoi is a partitioning of space plane such that for a collection of points where each point is contained within it’s own cell. We are guaranteed that each point will be isolated from each other point. This property can be used to great effect for mouse overs, so the user only mouses over a single point at a time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*wUKeEZHx328Pt6EJK4gx2w.png" /><figcaption>A colored in voronoi diagram, source <a href="https://en.wikipedia.org/wiki/Voronoi_diagram#/media/File:Euclidean_Voronoi_diagram.svg">wikipedia</a></figcaption></figure><p>We are imitating the mouseover setup found in the original NYT Graphic, where the plane is stripped into bands such that as you mouse up and down the currently selected player-year changes, and as you mouse left and right it stays the same. We can reconstruct this behavior by using a Voronoi with our specially built allPoints from before. Once implemented the layout of the voronoi cells will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*iAaF1xUXOyi3aL9br35rLw.png" /><figcaption>(When we’re done we will remove the stroke attribute from the Voronoi cells shown here, that way our user is none the wiser about our mouse over technique 😉)</figcaption></figure><p>Pretty cool! Now we’re ready to see the code for the interactive component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45c556910e8dc1242e04cb4dad19e628/href">https://medium.com/media/45c556910e8dc1242e04cb4dad19e628/href</a></iframe><p>Just as in our naive approach let’s go through the interesting parts one at a time. Let’s start with the elephant in the room:</p><pre>&lt;Voronoi<br>            extent={[<br>              [0, y(MAX_NUMBER_OF_THREE_POINTERS)], <br>              [width, height - margin.bottom]<br>            ]}<br>            nodes={allPoints}<br>            polygonStyle={{<br>              // UNCOMMENT BELOW TO SEE VORNOI<br>              stroke: &#39;rgba(0, 0, 0, .2)&#39;<br>            }}<br>            onHover={row =&gt; {<br>              const player = playerMap[`${row.pname}-${row.year}`];<br>              if (!player) {<br>                this.setState({<br>                  highlightSeries: null,<br>                  highlightTip: null<br>                });<br>                return;<br>              }<br>              this.debouncedSetState({<br>                highlightSeries: player.gameData,<br>                highlightTip: {<br>                  y: player.gameData[player.gameData.length - 1].y,<br>                  name: row.pname<br>                }<br>              });<br>            }}<br>            x={d =&gt; x(d.x)}<br>            y={d =&gt; y(d.y)}<br>            /&gt;</pre><p>This innocuous component takes in a list of points and builds a voronoi straight into the dom. It’s prop signature is a little bit anomalous compared to other components in react-vis (you need to provide it a scales, extent) so be careful! The other thing worth noting in this component is the use of the debouncedSetState function, which as you’ll note from above, we have to define via:</p><pre>componentWillMount() {<br>    this.debouncedSetState = debounce(newState =&gt;<br>      this.setState(newState), 40);<br>  }</pre><p>This function makes use of a lodash function called debounce which prevents a function from being called more than certain frequency (in this case once every 40 ms). Preventing this type of super fast state change is advantageous to us as we don’t want every time little motion the user makes to induce a state change. This would cause jitter and unnecessary redraws! To mask this little delay we add animation by including the animation prop on the LineSeries.</p><p>Putting this all together we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*v_Znzq64bzZwd8Kvn9YFqQ.gif" /><figcaption>Our pan-ultimate draft of the visualization</figcaption></figure><p>Modulo some small styling touches, that’s it! It operates smoothly and accurately reproduces the interaction found in the original visualization. Pretty dang cool!</p><h4>One more thing</h4><p>We’ve done pretty well at emulating the functionality of the original NYT visualization, but now we want to know: can we do better? The mouse over functionality that they present is reasonable, however it’s a little bit clunky and prevents you from mousing over every single player because of overlaps. We would like it if we could streamline this in a sensible and performant way. The answer to this problem, and, really if we’re being honest, most problems, is to make our Voronoi more nuanced.</p><p>A naive knee jerk would be to model create Voronoi cells for every data point. While it is totally possible to do this, it would create a lot of cells. If there are 82 games in the season for 750 players, that would be 61,500 distinct cells! A general rule of thumb says that the browser can only handle at most couple thousand SVG elements, so we need to be more clever.</p><p>A powerful solution is develop a simplified model of our dataset by simplifying each of our lines. Pleasantly there is a healthy body of work on the subject of line simplification, such as the ever excellent <a href="http://agafonkin.com/en/">Vladimir Agafonkin/mourner</a>’s <a href="http://mourner.github.io/simplify-js/">simplify-js</a> library. Much of this type of work has arisen because of cartographers interests in making shape preserving simplifications to the ragged edges of coast lines and other irregular geographic bodies. But we’ll put it to a different use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*w2cuVZtzoJeMdI3NiknaiQ.gif" /><figcaption>mourner’s <a href="http://mourner.github.io/simplify-js/">simplify-js</a> demo page, simplifying complex lines.</figcaption></figure><p>We will simplify each player-year’s line, so that we get the gist of the their line, without having too much detail. We execute on this idea by putting simplify-js to work on our data with another addition to utils file:</p><pre>const betterThanCurryLine = simplify(stephCurryRecord, 0.5)<br>    .map(({x, y}) =&gt;<br>        ({x, y: y + 20, pname: &#39;Stephen Curry&#39;, year: 2016}));</pre><pre>const SIMPLICATION = 3;<br>export function buildVoronoiPointsWithSimplification(data) {<br>  return data.reduce((acc, {player, pname, year, gameData}) =&gt; {<br>    return acc.concat(<br>      simplify(gameData, SIMPLICATION).map(({x, y}) =&gt; ({player, pname, year, x, y}))<br>    );<br>  }, betterThanCurryLine);<br>}</pre><p>Being visualizationists it is our first impulse to try to see what this these simplifications look like, and voila:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*YAe3HZvLp_DtOl3_Nxhcfg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*iJImkzX8LzfjYuee2Mw1QQ.png" /><figcaption>Visualization of the simplification of our model in preparation for a modest robust voronoi strategy (left) compared to the unsimplified data (right). On the left we that there is an (comparatively) jagged line above all of the others, this line is used to specially tune the character of the resulting voronoi. Curry’s record breaking trajectory plays a big role in the user’s experience of this chart, so it is necessary to provide some extra polish to make sure interactions with that line really shine.</figcaption></figure><p>With all of these pieces in place, we are, at last, ready to see the final voronoi in action. Behold:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*XlJrxILqlixKeql2f7R0hA.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*-n2TJ8w7nB-2HRTpPXAn9g.gif" /><figcaption>The user experience of using our line-simplified voronoi technique (left), and a visualization of what’s going on under the hood (right).</figcaption></figure><h4>Conclusion</h4><p>Over the course of this article we saw how to reconstruct a publication quality interactive data graphic using react-vis. This involved using a wide variety of interactive visualization techniques including canvas rendering, single pass rendering, debouncing, Voronois, and line simplification as a mechanism for tracing out line series. Not every visualization needs this many optimizations and advanced techniques, however we know a lot about our data and target behavior so we are able to tune it to be just the way we wanted.</p><p>In building our visualization we made heavy use of a number of features of react-vis, however the ideas discussed in this article are applicable to any web based visualization framework. You could easily implement these techniques in vanilla <a href="https://d3js.org/">d3</a>, <a href="https://github.com/emeeks/semiotic">semiotic</a>, or any of the huge host of other visualization tools available.</p><p>If you want to see the code in context, <a href="https://github.com/mcnuttandrew/advanced-react-vis-tutorial">check out this repo</a>. For additional advanced examples check out the <a href="https://uber.github.io/react-vis/examples/charts/streamgraph">charts section of the react-vis documentation</a> or some of my personal work, <a href="http://www.mcnutt.in/home-graphs/">like this</a>, or <a href="http://www.mcnutt.in/color-of-the-year/">this</a>, or maybe even <a href="http://www.mcnutt.in/city-size/">this</a>.</p><p>Happy visualizing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efc5c6667b4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/advanced-visualization-with-react-vis-efc5c6667b4">Advanced Visualization with react-vis</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>