Published
Edited
Jun 23, 2020
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
md`<figure>
<img src="${await FileAttachment("Draw_trerLayout.jpg").url()}">
</figure>`
Insert cell
Insert cell
category_array=["Sex", "Survived", "Age", "Class", "value"]
Insert cell
//Create a hierarchical format
//Nesting allows elements in an array to be grouped into a hierarchical tree structure.
//https://github.com/d3/d3-collection/blob/v1.0.7/README.md#nests
children = d3.nest()
.key(d => d[category_array[0]])
.key(d => d[category_array[1]])
.key(d => d[category_array[2]])
.key(d => d[category_array[3]])
//.key(d => d[category_array[4]])
.entries(data)
//The following code is to rename key - value pair into name - children pair
//https://stackoverflow.com/questions/17416186/d3-nest-key-and-values-conversion-to-name-and-children/17419311
//The map() method creates a new array with the results of calling a function for every array element.
//http://www.4codev.com/javascript/rename-all-object-keys-of-an-array-using-javascript-idpx2458097450239050230.html
.map(function(d){return{name: d.key, children:d.values
.map(function(sex){return {name: sex.key, children: sex.values
.map(function(age){return{name: age.key, children: age.values
.map(function(classes){return{name: classes.key, children: classes.values
.map(function(value){return {name: value.value}})}})}})}})}});

Insert cell
//d3.hierarchy object: a data structure that represents a hierarchy.
//https://observablehq.com/@d3/d3-hierarchy
titanicTree = d3.hierarchy({
children:children
})
Insert cell
//Draw the tree here using the graphTree function. It could look simlar to that.
//graphTree(hierarchyData, {label: d => d.data.name})

graphTree(titanicTree,{label: d => d.data.name})
Insert cell
//Add the depth and height information to the nested data
//https://www.d3indepth.com/layouts/
//https://www.developer.com/lang/jscript/creating-a-tree-diagram-with-d3.js.html
Insert cell
md` The tree graph needs nested data with specific information of the nodes, this includes height and depth. Have a look at the nest and hierarchy functionalities in D3. Remember to include the functionality to alter the order of the level in the tree according to the order in category_array.`
Insert cell
Insert cell
Insert cell
//Reference:
//https://github.com/d3/d3-sankey
//https://observablehq.com/@d3/parallel-sets
//https://jarrettmeyer.com/2018/05/31/creating-a-d3-sankey-graph
//https://www.d3-graph-gallery.com/graph/sankey_basic.html
parallelSet={
const svg = d3.create("svg").attr("viewBox", [0, 0, width, height]);
// your code
//Computes the node and link positions for the given arguments, returning a graph representing the Sankey layout.
const {nodes, links} = sankey({
//nodes: (feature of each elements)
//links: (how elements are connected)
//https://www.d3-graph-gallery.com/graph/sankey_basic.html
nodes: graph.nodes.map(d => Object.assign({}, d)),
links: graph.links.map(d => Object.assign({}, d))
});
//Node in svg
svg.append("g")
.selectAll("rect")
.data(nodes)
.join("rect")
.attr("x", d => d.x0)
.attr("y", d => d.y0)
.attr("height", d => d.y1 - d.y0)
.attr("width", d => d.x1 - d.x0)
.append("title")
.text(d => `${d.name}\n${d.value.toLocaleString()}`);
//Link in svg
svg.append("g")
.attr("fill", "none")
.selectAll("g")
.data(links)
.join("path")
.attr("d", d3.sankeyLinkHorizontal())
.attr("stroke", d => color(d.names[0]))
.attr("stroke-width", d => d.width)
.style("mix-blend-mode", "multiply")
.append("title")
.text(d => `${d.names.join(" → ")}\n${d.value.toLocaleString()}`);
//Attach information on each node
svg.append("g")
.style("font", "10px sans-serif")
.selectAll("text")
.data(nodes)
.join("text")
.attr("x", d => d.x0 < width / 2 ? d.x1 + 6 : d.x0 - 6)
.attr("y", d => (d.y1 + d.y0) / 2)
.attr("dy", "0.35em")
.attr("text-anchor", d => d.x0 < width / 2 ? "start" : "end")
.text(d => d.name)
.append("tspan")
.attr("fill-opacity", 0.7)
.text(d => ` ${d.value.toLocaleString()}`);


return svg.node();
}
Insert cell
//color for links
color = d3.scaleOrdinal(["Male"], ["#da4f81"]).unknown("#ccc")
Insert cell
//Create a sankey instance. This creates a function that can be used to generate our Sankey data.
sankey = d3.sankey()
.nodeSort(null)
.linkSort(null)
.nodeWidth(4)
.nodePadding(20)
.extent([[0, 5], [width, height - 5]])
Insert cell
//Graph: create nodes and links

graph = {
let index = -1;
const nodes = [];
const nodeByKey = new Map;
const indexByKey = new Map;
const links = [];

for (const k of keys) {
for (const d of data) {
const key = JSON.stringify([k, d[k]]);
if (nodeByKey.has(key)) continue;
const node = {name: d[k]};
nodes.push(node);
nodeByKey.set(key, node);
indexByKey.set(key, ++index);
}
}

for (let i = 1; i < keys.length; ++i) {
const a = keys[i - 1];
const b = keys[i];
const prefix = keys.slice(0, i + 1);
const linkByKey = new Map;
for (const d of data) {
const names = prefix.map(k => d[k]);
const key = JSON.stringify(names);
const value = d.value || 1;
let link = linkByKey.get(key);
if (link) { link.value += value; continue; }
link = {
source: indexByKey.get(JSON.stringify([a, d[a]])),
target: indexByKey.get(JSON.stringify([b, d[b]])),
names,
value
};
links.push(link);
linkByKey.set(key, link);
}
}

return {nodes, links};
}
Insert cell
keys = category_array.slice(0,4);
Insert cell
md`## Apendix`
Insert cell
data = d3.csvParse(await FileAttachment("titanic.csv").text(), d3.autoType)
Insert cell
import { table } from "@tmcw/tables/2"
Insert cell
dx = 12
Insert cell
dy = 90
Insert cell
Insert cell
tree = d3.tree().nodeSize([dx, dy])
Insert cell
shape2path = require("shape2path@3")
Insert cell
d3 = require("d3@5", "d3-sankey@0.12")
Insert cell
height=400
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more