Public
Edited
Apr 12
Insert cell
Insert cell
barley.json
Type Table, then Shift-Enter. Ctrl-space for more options.

Insert cell
Insert cell
{
// ---------- Build Hierarchy ----------
// Hierarchy: Barley (root) > Site > Year > Variety (leaf node with aggregated yield)
function buildHierarchy(data) {
const root = { name: "Barley", children: [] };
// Group data by site.
const sites = d3.group(data, d => d.site);
sites.forEach((siteRows, siteName) => {
const siteNode = { name: siteName, children: [] };

// Within a site, group data by year.
const years = d3.group(siteRows, d => d.year);
years.forEach((yearRows, year) => {
const yearNode = { name: String(year), children: [] };

// Within a year, group data by variety.
const varieties = d3.group(yearRows, d => d.variety);
varieties.forEach((varRows, varietyName) => {
// Sum yields in case there are multiple rows for the same variety.
const yieldSum = d3.sum(varRows, d => +d.yield);
const varietyNode = { name: varietyName, yield: yieldSum };
yearNode.children.push(varietyNode);
});

siteNode.children.push(yearNode);
});

root.children.push(siteNode);
});
return root;
}

// Build hierarchical data from the flat dataset stored in `barley`
const dataHierarchy = buildHierarchy(barley);

// Set dimensions and compute radius.
const width = 900;
const height = 900;
const radius = Math.min(width, height) / 2;

// Create a hierarchy from the data and sum up the yields at each node.
// Leaf nodes have the 'yield' property.
const rootData = d3.hierarchy(dataHierarchy)
.sum(d => d.yield)
.sort((a, b) => b.value - a.value);

// Compute the partition layout that sets angular and radial dimensions.
d3.partition().size([2 * Math.PI, radius])(rootData);

// Create an arc generator for the sunburst segments.
const arc = d3.arc()
.startAngle(d => d.x0)
.endAngle(d => d.x1)
.innerRadius(d => d.y0)
.outerRadius(d => d.y1);

// Create a color scale using the original rainbow scheme,
// which assigns colors based on the top-level (site) names.
const color = d3.scaleOrdinal(d3.quantize(d3.interpolateRainbow, rootData.children.length + 1));

// ---------- Create a Custom Tooltip ----------
const tooltip = d3.select(document.body)
.append("div")
.style("position", "absolute")
.style("pointer-events", "none")
.style("background", "rgba(255,255,255,0.95)")
.style("padding", "10px")
.style("border", "1px solid #aaa")
.style("border-radius", "4px")
.style("font-size", "16px")
.style("color", "#333")
.style("box-shadow", "2px 2px 5px rgba(0,0,0,0.3)")
.style("display", "none");

// ---------- Create the SVG Element ----------
const svg = d3.create("svg")
.attr("width", width)
.attr("height", height)
.attr("viewBox", [-width / 2, -height / 2, width, height])
.style("font", "10px sans-serif");

// Append a group element to hold the sunburst segments.
const g = svg.append("g");

// Draw the arcs – every node uses the same fill:
// It climbs to the top-level (site) and uses that color.
const paths = g.selectAll("path")
.data(rootData.descendants().filter(d => d.depth)) // Exclude the root node (depth 0)
.join("path")
.attr("d", arc)
.attr("fill", d => {
let current = d;
while (current.depth > 1) current = current.parent;
return d3.color(color(current.data.name)).brighter(0.5).toString();
})
// Use the default white stroke.
.attr("stroke", "#fff")
.attr("stroke-width", 1)
// ---- Attach event listeners for tooltip and highlighting ----
.on("mouseover", function(event, d) {
if (d.depth === 3) {
// For variety nodes, highlight all nodes sharing the same variety name.
paths.filter(dd => dd.depth === 3 && dd.data.name === d.data.name)
.attr("stroke", "black")
.attr("stroke-width", 3);
} else if (d.depth === 2) {
// For year nodes, highlight all nodes sharing the same year.
paths.filter(dd => dd.depth === 2 && dd.data.name === d.data.name)
.attr("stroke", "black")
.attr("stroke-width", 3);
} else {
d3.select(this).attr("stroke-width", 3);
}
tooltip.style("display", "block")
.html(`${d.ancestors().map(dd => dd.data.name).reverse().join(" > ")}<br><strong>Yield:</strong> ${d.value}`);
})
.on("mousemove", function(event) {
tooltip.style("left", (event.pageX + 10) + "px")
.style("top", (event.pageY + 10) + "px");
})
.on("mouseout", function(event, d) {
if (d.depth === 3) {
paths.filter(dd => dd.depth === 3 && dd.data.name === d.data.name)
.attr("stroke", "#fff")
.attr("stroke-width", 1);
} else if (d.depth === 2) {
paths.filter(dd => dd.depth === 2 && dd.data.name === d.data.name)
.attr("stroke", "#fff")
.attr("stroke-width", 1);
} else {
d3.select(this).attr("stroke-width", 1);
}
tooltip.style("display", "none");
});

// ---------- Add Text Labels ----------
// Add labels for all nodes (sites, years, and varieties).
// The labels are placed at the arc centroid (rotated for readability).
// For variety nodes (depth 3), always display text.
const texts = g.selectAll("text")
.data(rootData.descendants().filter(d => d.depth))
.join("text")
.attr("transform", d => {
const angle = (d.x0 + d.x1) / 2;
const [x, y] = arc.centroid(d);
const rotation = angle * 180 / Math.PI - 90;
return `translate(${x},${y}) rotate(${rotation})`;
})
.attr("dy", "0.35em")
.attr("text-anchor", "middle")
.text(d => d.data.name)
.style("fill", "black")
.style("font-size", d => (d.x1 - d.x0) > 0.3 ? "16px" : "10px")
.style("pointer-events", "none")
.style("opacity", d => d.depth === 3 ? 1 : ((d.x1 - d.x0) > 0.15 ? 1 : 0));

// ---------- Return the SVG Node (Observable will render it) ----------
return svg.node();
}
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