background preloader

Manipulating data like a boss with d3

Manipulating data like a boss with d3

How Selections Work Any sufficiently advanced technology is indistinguishable from magic. –Arthur C. Clarke In the past I have presented simplified descriptions of D3’s selections, providing only enough detail to get started. The structure of this article may at first seem arbitrary. D3 is a visualization library, so this article incorporates visual explanations to accompany the text. var array = [42]; Wherever possible, the code that generates the given selection appears immediately above the diagram. Let’s begin. #A Subclass of Array You were probably told that selections are arrays of DOM elements. #Grouping Elements Another reason selections aren’t literally arrays of elements is that they are arrays of arrays of elements: a selection is an array of groups, and each group is an array of elements. var selection ="body"); In the JavaScript console, try running this command and inspecting the group as selection[0] and the node as selection[0][0]. d3.selectAll("h2"); #Non-Grouping Operations

The world’s top 50 billionaires: A demographic breakdown. Top 50 Billionaire Breakdown If you asked anyone to picture the wealthiest person in the world at any given time, you could bet on some common denominators: probably a man; probably somehow attached to the words “multinational” or “conglomerate”; probably on a yacht off a private island. With Slate’s Top 50 Billionaire Breakdown, we attempt to visualize the richest of the rich by paring them into demographic categories: age, location, industry, source of wealth, education, and religious affiliation. Some of the sortings are heartening: There are more self-made men than born-rich kids in the top 50, and the self-made billionaires’ total wealth is bigger. Some are less so: The entire African continent has the same number of billionaires as Canada (one each), and there isn’t a single woman in the top 50 who’s self-made. Correction, Nov. 18, 2013: The interactive originally mislabeled the Koch brothers as Jewish.

xml - SQL Server SELECT to JSON function Home · mbostock/d3 Wiki Interactive Data Visualization for the Web Copyright © 2013 Scott Murray Printed in the United States of America. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles ( For more information, contact our corporate/institutional sales department: 800-998-9938 or <>. Nutshell Handbook, the Nutshell Handbook logo, the cover image, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. While every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein.

Thinking with Joins Say you’re making a basic scatterplot using D3, and you need to create some SVG circle elements to visualize your data. You may be surprised to discover that D3 has no primitive for creating multiple DOM elements. Wait, WAT? Sure, there’s the append method, which you can use to create a single element. svg.append("circle") .attr("cx", d.x) .attr("cy", d.y) .attr("r", 2.5); But that’s just a single circle, and you want many circles: one for each data point. svg.selectAll("circle") .data(data) .enter().append("circle") .attr("cx", function(d) { return d.x; }) .attr("cy", function(d) { return d.y; }) .attr("r", 2.5); This code does exactly what you need: it creates a circle element for each data point, using the x and y data properties for positioning. Here’s the deal. Data points joined to existing elements produce the update (inner) selection. Now we can unravel the mysterious enter-append sequence through the data join: But why all the trouble? Likewise, to shrink-out:

Adding an SVG Element | Basic Example In the last example you added a p HTML element to the DOM. In this example, you will use D3.js to add an SVG element to a basic webpage. Per our previous SVG examples , you will add an SVG circle to the webpage. Start with a basic HTML webpage: 1<! Recall that an SVG circle can be created as such: 1<svg width="50" height="50">2 <circle cx="25" cy="25" r="25" fill="purple" />3</svg> Next open the Developer Tools (Webkit Inspector)."body").append("svg").attr("width", 50).attr("height", 50).append("circle").attr("cx", 25).attr("cy", 25).attr("r", 25).style("fill", "purple"); This will give you the following: Congratulations - you've added an SVG element to the DOM using D3.js! D3.js Legibility As you progress further into D3.js, the code that you write will go from a few lines to potentially a couple hundred lines. It is hard to follow what is happening all the way through. JavaScript, much like HTML, does not care about white spaces or new line breaks. D3.js Chain Syntax

From Shapefile to GeoJSON - Jim Vallandingham A method for editing, merging, simplifying, and converting Shapefiles to GeoJSON D3.js supports cartographic visualizations by being able to display lines, polygons, and other geometry objects . It uses GeoJSON as the storage format for this type of visualization. Likewise, map tiling libraries like Leaflet can use GeoJSON to create map layers . You can find some GeoJSON files around, like in D3’s choropleth example , but sooner or later you will want to visualize a more specific portion of the world. Specifically, I am interested in visualizing census data for my hometown: Kansas City. Below is how I created a small GeoJSON file of just the KC metro from census shapefiles. WARNING: I am not an expert in GIS or cartography in general. Tools I’m using a mix of different applications to perform this conversion: Quantum GIS is used to deal with shapefiles. brew install gdal Initially I did run into an issue with homebrew when it was installing the geos prerequisite. Getting the Data And presto!

d3.legend example d3.legend d3.legend is a quick hack to add a legend to a d3 chart. Simply add a g and .call(d3.legend). Any elements that have a title set in the "data-legend" attribute will be included when d3.legend is called. Each title will appear only once (even when multiple items define the same data-legend) as the process uses a set based on a existing names, not an array of all items. Color By default the color in the legend will try to match the fill attribute or the stroke attribute of the relevant items. Order The order of items in the legend will be sorted using the top of the bounding box for each included item. Padding Padding will be determined by attribute "data-style-padding" on the legend element. Size Size of the box is determined by font size, as items are placed using "em" and the frame around the items is based on the bounding box. This Example This example takes an existing Gist and adds a legend by defining data-legend for each series and calling d3.legend on a "g" element.

Parallel Sets Titanic Survivors Explanation For each dimension (Survived, Sex, Age and Class), a horizontal bar is shown for each of its possible categories. The width of the bar denotes the absolute number of matches for that category. Starting with the first dimension (Survived), each of its categories is connected to a number of categories in the next dimension, showing how that category is subdivided. This subdividing is repeated recursively, producing a tree of “ribbons”. In fact, you can imagine Parallel Sets as being an icicle plot, with icicles of the same category being “bundled” together. Drag the dimensions and categories to reorder them. Women and Children First? We can see at a glance that the relative proportion of surviving women is far greater than that of the men. As for children, it becomes clearer when we drag the Age dimension up: around half the children survived. Do It Yourself The code is available as a reusable D3.js chart: d3.parsets. Alternatives Implementation Notes Discuss on HN!