Public
Edited
Jul 25, 2023
Insert cell
Insert cell
// Import D3.js library in ObservableHQ platform
import {d3} from "https://unpkg.com/d3@5/dist/d3.min.js"
Insert cell
let data = {
"name": "root",
"children": [
{"name": "Ping", "value": 704466319},
{"name": "NTP", "value": 2681492},
{"name": "DNS", "value": 219150484},
{"name": "SSL Cert", "value": 2812316},
{"name": "Traceroute", "value": 200526895},
{"name": "HTTP", "value": 75130906}
]
};
Insert cell


// Define dimensions
let width = 700;
let height = 500;

// Create a color scale
let color = d3.scaleOrdinal(d3.schemeCategory10);

// Define the treemap layout
let layout = d3.treemap()
.size([width, height])
.paddingInner(1);

// Create a root node
let root = d3.hierarchy(data).sum(function(d) { return d.value; });

layout(root);

// Create an SVG element
let svg = d3.select('body').append('svg')
.attr('width', width)
.attr('height', height);

// Add rectangles
svg.selectAll('rect')
.data(root.leaves())
.enter()
.append('rect')
.attr('x', function(d) { return d.x0; })
.attr('y', function(d) { return d.y0; })
.attr('width', function(d) { return d.x1 - d.x0; })
.attr('height', function(d) { return d.y1 - d.y0; })
.style('stroke', 'black')
.style('fill', function(d) { return color(d.data.name); });

// Add labels
svg.selectAll('text')
.data(root.leaves())
.enter()
.append('text')
.attr('x', function(d) { return d.x0+5; }) // +10 to adjust position (more right)
.attr('y', function(d) { return d.y0+20; }) // +20 to adjust position (lower)
.text(function(d) { return d.data.name + '\n' + d.data.value; })
.attr('font-size', '15px')
.attr('fill', 'white');

Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more