Public
Edited
Feb 25, 2023
Insert cell
Insert cell
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Icicle Plot Example</title>
<script src="https://d3js.org/d3.v5.min.js"></script>
</head>
<body>
<script>
// Define the width and height of the SVG canvas
const width = 600;
const height = 400;

// Define the data for the icicle plot
const data = {
name: 'Root',
children: [
{
name: 'Category A',
value: 10,
children: [
{ name: 'Subcategory 1', value: 5 },
{ name: 'Subcategory 2', value: 3 },
{ name: 'Subcategory 3', value: 2 }
]
},
{
name: 'Category B',
value: 12,
children: [
{ name: 'Subcategory 4', value: 7 },
{ name: 'Subcategory 5', value: 5 }
]
},
{
name: 'Category C',
value: 6,
children: [
{ name: 'Subcategory 6', value: 4 },
{ name: 'Subcategory 7', value: 2 }
]
}
]
};

// Create the root node for the hierarchy layout
const root = d3.hierarchy(data);

// Compute the size of each node in the hierarchy layout
root.sum(d => d.value);

// Create the color scale for the nodes
const color = d3.scaleOrdinal(d3.schemeCategory10);

// Create the layout for the icicle plot
const layout = d3.cluster()
.size([height, width - 160])
.separation((a, b) => (a.parent === b.parent ? 1 : 2) / a.depth);

// Compute the position of each node in the hierarchy layout
layout(root);

// Create the SVG canvas for the icicle plot
const svg = d3.select('body')
.append('svg')
.attr('width', width)
.attr('height', height)
.style('font', '10px sans-serif');

// Create the group element for the links
const linkGroup = svg.append('g')
.selectAll('path')
.data(root.links())
.enter().append('path')
.attr('d', d => `
M${d.source.y},${d.source.x}
L${d.target.y},${d.target.x}
`)
.attr('fill', 'none')
.attr('stroke', '#555')
.attr('stroke-opacity', 0.4)
.attr('stroke-width', d => Math.sqrt(d.source.value));

// Create the group element for the nodes
const nodeGroup = svg.append('g')
.selectAll('g')
.data(root.descendants())
.enter().append('g')
.attr('transform', d => `translate(${d.y},${d.x})`);

// Create the rectangle element for each node
const nodeRect = nodeGroup.append('rect')
.attr('fill', d => color(d.depth))
.attr('width', d => d.dy)
.attr('height', d => d.dx)
.attr('stroke', '#fff')
.attr('stroke-width', 1)
.on
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