Public
Edited
Jan 27, 2024
Insert cell
Insert cell
chart = {
// Specify the chart’s dimensions.
const width = 928;
const height = width;
const cx = width * 0.5; // adjust as needed to fit
const cy = height * 0.59; // adjust as needed to fit
const radius = Math.min(width, height) / 2 - 30;

// Create a radial tree layout. The layout’s first dimension (x)
// is the angle, while the second (y) is the radius.
const tree = d3.tree()
.size([2 * Math.PI, radius])
.separation((a, b) => (a.parent == b.parent ? 1 : 2) / a.depth);

// Sort the tree and apply the layout.
const root = tree(d3.hierarchy(data)
.sort((a, b) => d3.ascending(a.data.name, b.data.name)));

// Creates the SVG container.
const svg = d3.create("svg")
.attr("width", width)
.attr("height", height)
.attr("viewBox", [-cx, -cy, width, height])
.attr("style", "width: 100%; height: auto; font: 10px sans-serif;");

// Append links.
svg.append("g")
.attr("fill", "none")
.attr("stroke", "#555")
.attr("stroke-opacity", 0.4)
.attr("stroke-width", 1.5)
.selectAll()
.data(root.links())
.join("path")
.attr("d", d3.linkRadial()
.angle(d => d.x)
.radius(d => d.y));

// Define a color scale.
const color = d3.scaleSequential(d3.interpolateCool)
.domain(d3.extent(root.descendants(), d => d.data.value))


// Create the Legend
// Create a linear gradient that corresponds to the color scale.
const defs = svg.append("defs");
const gradient = defs.append("linearGradient")
.attr("id", "gradient");

gradient.selectAll("stop")
.data(color.ticks().map((t, i, n) => ({ offset: `${100*i/n.length}%`, color: color(t) })))
.join("stop")
.attr("offset", d => d.offset)
.attr("stop-color", d => d.color);

// Add a rectangle that uses the gradient.
const legendWidth = 300;
const legendHeight = 20;
svg.append("rect")
.attr("width", legendWidth)
.attr("height", legendHeight)
.style("fill", "url(#gradient)")
.attr("transform", `translate(${cx - legendWidth / 2}, ${cy + radius + 30})`); // Adjust translation as needed
// Add an axis to represent the values.
const legendScale = d3.scaleLinear()
.domain(color.domain())
.range([0, legendWidth]);
const legendAxis = d3.axisBottom(legendScale).ticks(5);
svg.append("g")
.attr("transform", `translate(${cx - legendWidth / 2}, ${cy + radius + 50})`) // Adjust translation as needed
.call(legendAxis);

// Append nodes.
svg.append("g")
.selectAll()
.data(root.descendants())
.join("circle")
.attr("transform", d => `rotate(${d.x * 180 / Math.PI - 90}) translate(${d.y},0)`)
.attr("fill", d => color(d.data.value))
.attr("r", 5);


return svg.node();
}




Insert cell
data = FileAttachment("JSON_Hierarchical_Data_True_v2.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