Public
Edited
Apr 12
1 star
Insert cell
Insert cell
// Battalion selection box (multi-select)
viewof battalionFilter = Inputs.checkbox(
["All Battalions", ...new Set(data.map((d) => d.Battalion))].sort(),
{
label: "Select Battalion",
value: ["All Battalions"] // Default to "All Battalions"
}
)
Insert cell
// Year selection box
viewof yearFilter = Inputs.select(
["All Years", ...new Set(data.map((d) => d.Year))].sort(),
{ label: "Select Year" }
)
Insert cell
chart = {
// Specify the chart dimensions
const width = 1200;

// Compute the tree layout
const root = filteredHierarchyData;

const maxDepth = d3.max(root.descendants(), (d) => d.depth);
const marginLeft = Math.max(40, (maxDepth + 1) * 10);
const marginRight = Math.max(10, (maxDepth + 1) * 10);
const marginTop = Math.max(10, (maxDepth + 1) * 10);
const marginBottom = Math.max(10, (maxDepth + 1) * 10);
const dx = 20;
const dy = (width - marginRight - marginLeft) / (1 + root.height);

const treeLayout = d3.tree().nodeSize([dx, dy]);

// Define color scale
const maxCount = d3.max(root.descendants(), (d) => d.value) || 1;
const colorScale = d3.scaleOrdinal(d3.schemeTableau10).domain([0, maxCount]);

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

// Create the SVG container
const svg = d3
.create("svg")
.attr("width", width)
.attr("viewBox", [-marginLeft, -marginTop, width, dx])
.style("max-width", "100%")
.style("height", "auto")
.style("font", "15px sans-serif");

// Create layers for links and nodes
const gLink = svg
.append("g")
.attr("fill", "none")
.attr("stroke", "#555")
.attr("stroke-opacity", 0.4)
.attr("stroke-width", 1.5);

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

// Update function for rendering and transitioning the tree
function update(event, source) {
const duration = event?.altKey ? 2500 : 250; // Hold alt key to slow down transitions
const nodes = root.descendants().reverse();
const links = root.links();

// Compute the new tree layout
treeLayout(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 height = right.x - left.x + marginTop + marginBottom;

const transition = svg
.transition()
.duration(duration)
.attr("viewBox", [-marginLeft, left.x - marginTop, width, height])
.tween(
"resize",
window.ResizeObserver ? null : () => () => svg.dispatch("toggle")
);

// Update the nodes
const node = gNode.selectAll("g").data(nodes, (d) => d.id);

// Enter 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) => {
if (d.children) {
// Collapse: store children in _children before nullifying
d._children = d.children;
d.children = null;
} else if (d._children) {
// Expand: restore children from _children
d.children = d._children;
d._children = null;
} else {
// Handle leaf nodes (no children to toggle)
return;
}
update(event, d);
});

// Add tooltip functionality
nodeEnter.append("title").text((d) => {
const path = d
.ancestors()
.reverse()
.map((n) => n.data.name)
.join(" → ");
return `${path}\nCount: ${d.value || 1}`;
});

// Define a scaling function for circle sizes
const maxCount = d3.max(root.descendants(), (d) => d.value) || 1;
const sizeScale = d3.scaleSqrt().domain([0, maxCount]).range([5, 50]); // Minimum radius = 5, Maximum radius = 50

nodeEnter
.append("circle")
.attr("r", (d) => {
const scaledSize = sizeScale(d.value || 1);
return Math.min(scaledSize, 50);
}) // Cap the radius
.attr("fill", (d) => colorScale(d.value)) // Color collapsed vs expanded nodes
.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)
.attr("stroke-linejoin", "round")
.attr("stroke-width", 3)
.attr("stroke", "white")
.attr("paint-order", "stroke");

// 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);

// Enter 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 });
});

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

// Transition exiting links 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;
});
}

// Initialize the tree
root.x0 = dx / 2;
root.y0 = 0;
root.descendants().forEach((d, i) => {
d.id = i;
if (d.depth >= 1) {
d._children = d.children; // Store children in _children
d.children = null; // Collapse nodes beyond Battalion level initially
}
});

update(null, root);

return svg.node();

// Add color legend
const legend = svg
.append("g")
.attr("transform", `translate(${width - 150}, 20)`) // Position legend in top-right corner
.selectAll(".legend")
.data(colorScale.domain())
.join("g")
.attr("class", "legend")
.attr("transform", (d, i) => `translate(0, ${i * 20})`);

legend
.append("rect")
.attr("width", 18)
.attr("height", 18)
.attr("fill", (d) => colorScale(d));

legend
.append("text")
.attr("x", 24)
.attr("y", 9)
.attr("dy", "0.35em")
.text((d) => `Level ${d}`);

return svg.node();
}
Insert cell
filteredHierarchyData = {
const root = { name: "Fire Incidents", children: [] };

// Filter data by selected Year and Battalion
const filteredData = data.filter((d) => {
const yearMatch = yearFilter === "All Years" || d.Year === yearFilter;
// Handle multiple Battalion selections
const battalionMatch =
battalionFilter.includes("All Battalions") ||
battalionFilter.includes(d.Battalion);
return yearMatch && battalionMatch;
});

// Build the hierarchy from the filtered data
d3.group(
filteredData,
(d) => d.Battalion,
(d) => d.Station,
(d) => d.ResponseCat,
(d) => d.OnSceneCat,
(d) => d.ClearCat
).forEach((battalion, battalionName) => {
const battalionNode = { name: battalionName, children: [] };

battalion.forEach((station, stationName) => {
const stationNode = { name: stationName, children: [] };

station.forEach((response, responseCat) => {
const responseNode = { name: responseCat, children: [] };

response.forEach((scene, sceneCat) => {
const sceneNode = { name: sceneCat, children: [] };

scene.forEach((clear, clearCat) => {
sceneNode.children.push({
name: clearCat,
value: clear.length // Count of incidents
});
});

responseNode.children.push(sceneNode);
});

stationNode.children.push(responseNode);
});

battalionNode.children.push(stationNode);
});

root.children.push(battalionNode);
});

return d3.hierarchy(root).sum((d) => d.value || 1); // Summarize counts
}
Insert cell
// Build hierarchical structure
hierarchyData = {
const root = { name: "Fire Incidents", children: [] };

d3.group(
data,
(d) => d.Battalion,
(d) => d.Station,
(d) => d.ResponseCat,
(d) => d.OnSceneCat,
(d) => d.ClearCat
).forEach((battalion, battalionName) => {
const battalionNode = { name: battalionName, children: [] };

battalion.forEach((station, stationName) => {
const stationNode = { name: stationName, children: [] };

station.forEach((response, responseCat) => {
const responseNode = { name: responseCat, children: [] };

response.forEach((scene, sceneCat) => {
const sceneNode = { name: sceneCat, children: [] };

scene.forEach((clear, clearCat) => {
sceneNode.children.push({
name: clearCat,
value: clear.length // Count of incidents
});
});

responseNode.children.push(sceneNode);
});

stationNode.children.push(responseNode);
});

battalionNode.children.push(stationNode);
});

root.children.push(battalionNode);
});

return root;
}
Insert cell
// Load and process data
data = FileAttachment("combined_data_20-22.csv")
.csv({ typed: true })
.then((data) => {
return data
.map((d, i) => {
// Correct date parsing for "MM/DD/YYYY hh:mm AM/PM"
const parseTime = d3.timeParse("%m/%d/%Y %H:%M");

// Parse dates with detailed validation
const parseValidTime = (timeStr, fieldName) => {
if (!timeStr || timeStr.trim() === "") {
console.warn(`Row ${i + 1}: Missing value for ${fieldName}`);
return null;
}
const date = parseTime(timeStr.trim());
if (!date || isNaN(date)) {
console.warn(
`Row ${i + 1}: Invalid date for ${fieldName}: "${timeStr}"`
);
return null;
}
return date;
};

const eventTime = parseValidTime(
d["Date_Time_Of_Event"],
"Date_Time_Of_Event"
);
const dispatched = parseValidTime(
d["Dispatched_Time"],
"Dispatched_Time"
);
const onScene = parseValidTime(
d["Unit_On_Scene_TimeStamp"],
"Unit_On_Scene_TimeStamp"
);
const cleared = parseValidTime(
d["Cleared_TimeStamp"],
"Cleared_TimeStamp"
);

// Skip invalid rows
if (![eventTime, dispatched, onScene, cleared].every((d) => d)) {
console.warn(`Row ${i + 1}: Skipped due to invalid or missing dates`);
return null;
}

// Calculate time differences in minutes
const responseTime = (dispatched - eventTime) / (1000 * 60);
const onSceneTime = (onScene - dispatched) / (1000 * 60);
const clearTime = (cleared - onScene) / (1000 * 60);

return {
...d,
Year: eventTime.getFullYear(),
ResponseTime: Math.round(responseTime),
OnSceneTime: Math.round(onSceneTime),
ClearTime: Math.round(clearTime),
ResponseCat: responseTime > 3 ? "Response >3 min" : "Response ≤3 min",
OnSceneCat: onSceneTime > 5 ? "On Scene >5 min" : "On Scene ≤5 min",
ClearCat: clearTime > 10 ? "Clear >10 min" : "Clear ≤10 min"
};
})
.filter((d) => d); // Remove invalid rows
})
Insert cell
// Inspect raw data
rawdata = FileAttachment("combined_data_20-22.csv").csv({ typed: true })
Insert cell
rawdata1 = FileAttachment("2020.csv").csv({ typed: true })
Insert cell
// Import the Tree component first
import { Tree } from "@d3/tree-component"
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