Going from Tabular data to nested for visualizing hierarchy, wanting to plug into d3.hierarchy examples

Have been looking into d3.hierarchy, but am having trouble wrangling my data to be in a nested format that matches the examples. I have a case similar to the tabular data, with nesting regions that ultimately define values (like the earnings by nation and sport)

I’d like to be able to plug in my data to the different tree formats, but the data used (flare.json) is nested Objects rather than tabular data. Is there a way to go from tabular data to a nested JSON object?

Would like to:

  • convert tabular data to nested objects
  • use d3.hierarchy to convert to a nested structure for a tree

Here is a notebook outlining it.

Another approach: I was thinking the easiest thing to do was to get my tabular data in the same format as the examples. Is there another way to modify the viz code?

1 Like

You can pass either hierarchical data or tabular data to the Treemap component, and other reusable D3 charts.

For example, assuming your data is defined like so:

group = d3.group(data, d => d.nation, d => d.sport, d => d.name)

You can create a treemap like so:

Treemap(group, {
  value: d => d.earnings,
  group: d => d.sport,
  label: (d, n) => [d.name, d.nation, d.sport, n.value].join("\n")
import {Treemap} from "@d3/treemap"

Or a circle-packing diagram like so:

Pack(group, {
  value: d => d.earnings,
  label: (d, n) => [d.name, d.nation, d.sport, n.value].join("\n")
import {Pack} from "@d3/pack"

Or a tidy tree like so:

Tree(group, {
  value: d => d.earnings,
  label: (d, n) => n.data[0] || d.earnings
import {Tree} from "@d3/tree"

Fantastic, works like a charm!

Lingering pseudo-related question: when using d3.hierarchy in Observable, the output is “Zh” for d3@6 and “pd” for the d3 that is loaded by default. Any insight into what these mean? Much appreciated.

These are the names given by the minifier; you can load an unminified version of d3 instead with

d3 = require(“d3@7/dist/d3.js”)

and then you’ll see that this name is Node$1 (the $1 indicating that it is the second occurrence of Node that the bundler has found and renamed).

1 Like

Interesting, thanks Fil. As expected, learning more reveals a highly nested path to explore further. Thanks so much.