Public
Edited
Feb 7, 2024
Insert cell
Insert cell
viewof depth = Inputs.range([0, 20], {value: 17, step: 1, label: "Tree Depth"})
Insert cell
chart = {

// Specify the charts’ dimensions. The height is variable, depending on the layout.
const width = 928;
const height = 600;
const marginTop = 10;
const marginRight = 10;
const marginBottom = 10;
const marginLeft = 40;

// Rows are separated by dx pixels, columns by dy pixels. These names can be counter-intuitive
// (dx is a height, and dy a width). This because the tree must be viewed with the root at the
// “bottom”, in the data domain. The width of a column is based on the tree’s height.
const root = d3.hierarchy(data);
const dx = 10;
const dy = 40;
//const dy = width - marginRight - marginLeft) / (1 + root.height);

// Define the tree layout and the shape for links.
const tree = d3.tree().nodeSize([dx, dy]);

const h = new Set();
root.leaves().forEach((leaf, k) => {
if (k === 13) {
// Get ancestors that meet the name condition
const ancestorsMeetingCondition = leaf.ancestors().filter(ancestor => ancestor.data.name * 1 < 0.10);
// For each qualifying ancestor, add its descendants to the set
ancestorsMeetingCondition.forEach(ancestor => {
ancestor.descendants().forEach(descendant => {
h.add(descendant);
});
});
}
});
const highlight = d => h.has(d);

//const diagonal = d3.linkRadial().angle(d => {return d.depth === 0 ? Math.PI/2 : (Math.PI - Math.atan2(d.y, d.x))}).radius(d => Math.hypot(d.x, d.y))

//const diagonal = d3.linkVertical().x(d => d.y).y(d => d.x);

const diagonal = d3.linkHorizontal().x(d => d.y).y(d => d.x);

// Create the SVG container, a layer for the links and a layer for the nodes.
const svg = d3.create("svg")
.attr("width", width)
.attr("height", height) //was dx
.attr("viewBox", [-marginLeft, -marginTop, width, height]) //was dx
.attr("style", "max-width: 100%; height: " + height + "; font: 10px sans-serif; user-select: none;");

const gLink = svg.append("g")
.attr("fill", "none")
.attr("stroke", "#555")
.attr("stroke-opacity", 0.3)
.attr("stroke-width", 1.0)

const gNode = svg.append("g")
.attr("cursor", "pointer")
.attr("pointer-events", "all");

function update(event, source) {
const duration = event?.altKey ? 2500 : 250; // hold the alt key to slow down the transition
const nodes = root.descendants().reverse();
const links = root.links();

// Compute the new tree layout.
tree(root);

let left = root;
let right = root;
root.eachBefore(node => {
if (node.x < left.x) left = node;
if (node.x > right.x) right = node;
});

const autoHeight = right.x - left.x + marginTop + marginBottom;

const transition = svg.transition()
.duration(duration)
.attr("height", autoHeight)
.attr("viewBox", [-marginLeft, left.x - marginTop, width, autoHeight])
.tween("resize", window.ResizeObserver ? null : () => () => svg.dispatch("toggle"));
// Update the nodes…
const node = gNode.selectAll("g")
.data(nodes, d => d.id);

// Enter any new nodes at the parent's previous position.
const nodeEnter = node.enter().append("g")
.attr("transform", d => `translate(${source.y0},${source.x0})`)
.attr("fill-opacity", 0)
.attr("stroke-opacity", 0)
.on("click", (event, d) => {
d.children = d.children ? null : d._children;
update(event, d);
});

nodeEnter.append("circle")
.attr("r", 2.5)
.attr("fill", d => d._children ? "#555" : "#999")
.attr("stroke-width", 10);

nodeEnter.append("text")
.attr("dy", "0.31em")
.attr("x", d => d._children ? -6 : 6)
.attr("text-anchor", d => d._children ? "end" : "start")
.text(d => d.data.name.replace("0.","."))
.clone(true).lower()
.attr("stroke-linejoin", "round")
.attr("stroke-width", 3)
.attr("stroke", "white");

nodeEnter.filter(d => !d.children && !d._children) // Filter for leaf nodes
.append("image")
.attr("xlink:href", d => d.data.image) // Assuming the image URL is stored in the node's data under 'image'
.attr("x", "-8px") // Set image position and size as needed
.attr("y", "-8px")
.attr("width", "16px")
.attr("height", "16px");

// Transition nodes to their new position.
const nodeUpdate = node.merge(nodeEnter).transition(transition)
.attr("transform", d => `translate(${d.y},${d.x})`)
.attr("fill-opacity", 1)
.attr("stroke-opacity", 1);

// Transition exiting nodes to the parent's new position.
const nodeExit = node.exit().transition(transition).remove()
.attr("transform", d => `translate(${source.y},${source.x})`)
.attr("fill-opacity", 0)
.attr("stroke-opacity", 0);

// Update the links…
const link = gLink.selectAll("path")
.data(links, d => d.target.id)
.attr("stroke", d => highlight(d.source) && highlight(d.target) ? "red" : null)
.attr("stroke-opacity", d => highlight(d.source) && highlight(d.target) ? 1 : null)

// Enter any new links at the parent's previous position.
const linkEnter = link.enter().append("path")
.attr("d", d => {
const o = {x: source.x0, y: source.y0};
return diagonal({source: o, target: o});
})
.attr("stroke", d => highlight(d.source) && highlight(d.target) ? "red" : null)
.attr("stroke-opacity", d => highlight(d.source) && highlight(d.target) ? 1 : null)
;

// Transition links to their new position.
link.merge(linkEnter).transition(transition)
.attr("d", diagonal);

// Transition exiting nodes to the parent's new position.
link.exit().transition(transition).remove()
.attr("d", d => {
const o = {x: source.x, y: source.y};
return diagonal({source: o, target: o});
});

// Stash the old positions for transition.
root.eachBefore(d => {
d.x0 = d.x;
d.y0 = d.y;
});
}

// Do the first update to the initial configuration of the tree — where a number of nodes
// are open (arbitrarily selected as the root, plus nodes with 7 letters).


// Initialize the tree with all nodes expanded by ensuring `d.children` is always set.
root.x0 = dy / 2;
root.y0 = 0;
root.descendants().forEach((d, i) => {
d.id = i;
// Ensure all nodes are expanded by keeping the original children in `d.children`
d._children = d.children; // Keep a reference to the children but don't use it to collapse nodes.
// Do not collapse any nodes, so no need to set `d.children` to null based on any condition
if (d.depth >= depth) d.children = null;

});

update(null, root); // Perform the initial update to render the tree with all nodes expanded


// Set up the zoom functionality
svg.call(d3.zoom()
.extent([[0, 0], [width, height]]) // Use initialHeight for the extent
.scaleExtent([0.5, 5]) // Adjusted the scale extent to allow for more zoom out (0.5)
.on("zoom", zoomed));
function zoomed(event) {
// Apply the zoom transformation to both gLink and gNode
gLink.attr("transform", event.transform);
gNode.attr("transform", event.transform);
}

return svg.node();
}
Insert cell
data = FileAttachment("photos-test-clu.json").json()
Insert cell
Insert cell
{
var root = d3.hierarchy(data, d => d.children);
return graph(root);
}
Insert cell
tree = d3.tree().nodeSize([12, 12])
Insert cell
Insert cell
function graph(root, {
label = d => d.data.id,
marginLeft = 40
} = {}) {
root = tree(root);
const h = new Set(root.leaves()[13].ancestors());
const highlight = d => h.has(d);
let x0 = Infinity;
let x1 = -x0;
root.each(d => {
if (d.x > x1) x1 = d.x;
if (d.x < x0) x0 = d.x;
});

const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, x1 - x0 + 12 * 2])
.style("overflow", "visible");
const g = svg.append("g")
.attr("font-family", "sans-serif")
.attr("font-size", 10)
.attr("transform", `translate(${marginLeft},${12 - x0})`);
const link = g.append("g")
.attr("fill", "none")
.attr("stroke", "#555")
.attr("stroke-opacity", 0.4)
.attr("stroke-width", 1.5)
.selectAll("path")
.data(root.links())
.join("path")
.attr("stroke", d => highlight(d.source) && highlight(d.target) ? "red" : null)
.attr("stroke-opacity", d => highlight(d.source) && highlight(d.target) ? 1 : null)
.attr("d", treeLink);
const node = g.append("g")
.attr("stroke-linejoin", "round")
.attr("stroke-width", 3)
.selectAll("g")
.data(root.descendants())
.join("g")
.attr("transform", d => `translate(${d.y},${d.x})`);

node.append("circle")
.attr("fill", d => highlight(d) ? "red" : d.children ? "#555" : "#999")
.attr("r", 2.5);

node.append("text")
.attr("fill", d => highlight(d) ? "red" : null)
.attr("stroke", "white")
.attr("paint-order", "stroke")
.attr("dy", "0.31em")
.attr("x", d => d.children ? -6 : 6)
.attr("text-anchor", d => d.children ? "end" : "start")
.text(label);
return svg.node();
}
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