Public
Edited
Dec 9, 2023
Insert cell
Insert cell
// Specify the chart’s dimensions.
chart = {
const width = 800;
const height = 900;
const someAdditionalWidth = 600; // Additional space for breadcrumbs

// Define a color scale
const color = d3
.scaleOrdinal()
.domain([0, 1, 2, 3, 4, 5]) // Adjust the domain based on the number of levels in your tree
.range([
"oldlace",
"Indianred",
"sandybrown",
"khaki",
"LightSteelBlue",
"olivedrab",
"plum"
]);

// This custom tiling function adapts the built-in binary tiling function
// for the appropriate aspect ratio when the treemap is zoomed-in.
function tile(node, x0, y0, x1, y1) {
d3.treemapBinary(node, 0, 0, width, height);
for (const child of node.children) {
child.x0 = x0 + (child.x0 / width) * (x1 - x0);
child.x1 = x0 + (child.x1 / width) * (x1 - x0);
child.y0 = y0 + (child.y0 / height) * (y1 - y0);
child.y1 = y0 + (child.y1 / height) * (y1 - y0);
}
}

// Compute the layout.
const hierarchy = d3
.hierarchy(data)
.sum((d) => d.value)
.sort((a, b) => b.value - a.value);
const root = d3.treemap().tile(tile)(hierarchy);

// Create the scales.
const x = d3.scaleLinear().rangeRound([0, width]);
const y = d3.scaleLinear().rangeRound([0, height]);

// Formatting utilities.
const format = d3.format(",d");
const name = (d) =>
d
.ancestors()
.reverse()
.map((d) => d.data.name)
.join("/");

// Create the SVG container.
const svg = d3
.create("svg")
.attr("viewBox", [0.5, -30.5, width, height + 30])
.attr("width", width + someAdditionalWidth)
.attr("height", height)
.attr("style", "max-width: 100%; max-height: 100%;")
.style("font", "13px sans-serif");

const hierarchyCircles = svg
.append("g")
.attr("class", "hierarchy-circles")
.attr("transform", `translate(${width + 100}, 300)`); // Adjust position as needed

function wrapText(selection, radius) {
selection.each(function (d) {
const node = d3.select(this);
let textLength = node.node().getComputedTextLength();
let text = node.text();
while (textLength > (radius - 2) * 2 && text.length > 0) {
text = text.slice(0, -1);
node.text(text + "...");
textLength = node.node().getComputedTextLength();
}
});
}

function handleMouseOver(d, i) {
// Increase stroke width and change color for highlight effect
d3.select(this).style("stroke", "white").style("stroke-width", 3);
}

function handleMouseOut(d, i) {
// Revert to original style
d3.select(this).style("stroke", "white").style("stroke-width", 1);
}

function updatePathText(node) {
const pathNodes = node.ancestors().reverse(); // Exclude the root node
const bubbleRadius = 50; // Increased radius for larger bubbles

// Select or create the breadcrumbs group
let breadcrumbs = svg.select(".breadcrumbs");
if (breadcrumbs.empty()) {
breadcrumbs = svg
.append("g")
.attr("class", "breadcrumbs")
.attr("transform", `translate(${width + 100}, 100)`); // Position further to the right
}

// Create a group for each breadcrumb

const breadcrumbGroups = breadcrumbs
.selectAll("g.breadcrumb")
.data(pathNodes, (d) => d.data.name)
.join("g")
.attr("class", "breadcrumb")
.attr(
"transform",
(d, i) => `translate(0, ${i * (bubbleRadius * 2 + 20)})`
) // Adjust spacing between bubbles
.on("click", (d) => zoomToNode(d));

breadcrumbGroups.exit().remove();

// Create circles for each breadcrumb
breadcrumbGroups
.append("circle")
.attr("r", bubbleRadius)
.attr("fill", (d) => color(d.depth + 1)) // Use the same color scale as the treemap
.style("stroke-width", 1.9) // set the stroke width
.style("stroke", "black");

breadcrumbGroups.on("click", (event, d) => {
// Prevent default action if necessary.
event.preventDefault();

// Zoom to the clicked breadcrumb's corresponding node.
zoomToNode(d);
});

breadcrumbGroups
.append("text")
.attr("text-anchor", "middle")
.attr("dy", "0.35em")
.text((d) => {
// Assuming each node has a 'key' attribute you want to display
const keyInfo = d.data.value ? `: ${d.data.value}` : "";
return `${d.data.name}${keyInfo}`;
})
.style("font", "14px sans-serif")
.style("font-weight", "semi-bold")
.call(wrapText, bubbleRadius); // wrapText function as defined earlier
}

function zoomToNode(targetNode) {
const group0 = group.attr("pointer-events", "none");
const group1 = (group = svg.append("g").call(render, targetNode));

x.domain([targetNode.x0, targetNode.x1]);
y.domain([targetNode.y0, targetNode.y1]);

svg
.transition()
.duration(750)
.call((t) =>
group0.transition(t).remove().call(position, targetNode.parent)
)
.call((t) =>
group1
.transition(t)
.attrTween("opacity", () => d3.interpolate(0, 1))
.call(position, targetNode)
);

updatePathText(targetNode); // Update the path text
}

// Display the root.
let group = svg.append("g").call(render, root);
// Initial call to display the root path

function render(group, root) {
const node = group
.selectAll("g")
.data(root.children.concat(root))
.join("g");

node
.filter((d) => (d === root ? d.parent : d.children))
.attr("cursor", "pointer");
node.on("click", (event, d) => {
// Prevent default behavior for shift-click
if (event.shiftKey) {
event.preventDefault();

// Check if it's the root node or a leaf node
if (d === root || !d.children) {
// Open Wikipedia search
const searchQuery = d === root ? root.data.name : d.data.name;
window.open(
`https://en.wikipedia.org/w/index.php?search=${encodeURIComponent(
searchQuery,
"_blank",
"width=200,height=100"
)}`
);
}
if (event.shiftKey) {
window.open(
`https://en.wikipedia.org/w/index.php?search=${encodeURIComponent(
d.data.name,
"_blank",
"width=200,height=100"
)}`
);
}
} else {
// Handle non-shift click (zoom in or out)
d === root ? zoomout(root) : zoomin(d);
}
});
node.append("title").text((d) => `${name(d)}\n${format(d.value)}`);

node
.append("rect")
.attr("id", (d) => (d.leafUid = DOM.uid("leaf")).id)
.attr("fill", (d) => (d.depth === 0 ? "#fff" : color(d.depth)))
.attr("stroke", "#fff")
.on("mouseover", handleMouseOver)
.on("mouseout", handleMouseOut);

node
.append("clipPath")
.attr("id", (d) => (d.clipUid = DOM.uid("clip")).id)
.append("use")
.attr("xlink:href", (d) => d.leafUid.href);

node
.append("text")
.attr("clip-path", (d) => d.clipUid)
.attr("font-weight", (d) => (d === root ? "bold" : null))
.selectAll("tspan")
.data((d) =>
(d === root ? name(d) : d.data.name)
.split(/(?=[A-Z][^A-Z])/g)
.concat(format(d.value))
)
.join("tspan")
.attr("x", 3)
.attr(
"y",
(d, i, nodes) => `${(i === nodes.length + 4) * 0.3 + 1.1 + i * 0.9}em`
)
.attr("fill-opacity", (d, i, nodes) =>
i === nodes.length - 1 ? 0.7 : null
)
.attr("font-weight", (d, i, nodes) =>
i === nodes.length - 1 ? "normal" : null
)
.text((d) => d);

group.call(position, root);
}

function position(group, root) {
group
.selectAll("g")
.attr("transform", (d) =>
d === root ? `translate(0,-30)` : `translate(${x(d.x0)},${y(d.y0)})`
)
.select("rect")
.attr("width", (d) => (d === root ? width : x(d.x1) - x(d.x0)))
.attr("height", (d) => (d === root ? 30 : y(d.y1) - y(d.y0)));
}

// When zooming in, draw the new nodes on top, and fade them in.
function zoomin(d) {
zoomToNode(d);
}

function zoomout(d) {
// Check if the clicked node has a parent.
if (!d.parent) return; // If no parent, do nothing (we're at the root)

// Set the x and y domain to the parent node's dimensions.
x.domain([d.parent.x0, d.parent.x1]);
y.domain([d.parent.y0, d.parent.y1]);

// Re-render the visualization with the parent node.
const group0 = group.attr("pointer-events", "none");
const group1 = (group = svg.insert("g", "*").call(render, d.parent));

// Transition for zooming out.
svg
.transition()
.duration(750)
.call((t) =>
group0
.transition(t)
.remove()
.attrTween("opacity", () => d3.interpolate(1, 0))
.call(position, d)
)
.call((t) => group1.transition(t).call(position, d.parent));

// Update breadcrumbs if needed.
updatePathText(d.parent);
}

function wrapSvgText(text, width) {
text.each(function () {
var text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1.1, // ems
y = text.attr("y"),
dy = 0, // we start with a dy of 0
tspan = text
.text(null)
.append("tspan")
.attr("x", 0)
.attr("y", y)
.attr("dy", dy + "em");

while ((word = words.pop())) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
line.pop(); // remove the last word
tspan.text(line.join(" ")); // set the text without the last word
line = [word]; // start a new line with the last word
tspan = text
.append("tspan")
.attr("x", 0)
.attr("y", y)
.attr("dy", `${++lineNumber * lineHeight + dy}em`)
.text(word);
}
}
});
}

updatePathText(root);

return svg.node();
}
Insert cell
data = FileAttachment("national_parks_data_w_species@12.json").json()
Insert cell
national_parks_data_w_species3 = FileAttachment("national_parks_data_w_species@12.json").json()
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