Public
Edited
Jan 13, 2023
4 stars
Insert cell
Insert cell
{
const svg = d3.create("svg")
.attr("width", chartwidth + margin.left + margin.right)
.attr("height", chartheight + margin.top + margin.bottom);

const g = svg.append("g")
.attr("transform", `translate(${[margin.left, margin.top]})`);

g.selectAll("path")
.data(stacked)
.join("path")
.attr("fill", d => colorScale(d.key))
.attr("stroke", d => colorScale(d.key))
.attr("d", area);

yield svg.node();
g.selectAll(".area-label")
.data(stacked)
.join("text")
.attr("class", "area-label")
.text(d => d.key)
.attr("transform", d3.areaLabel(area));

return svg.node();
}
Insert cell
data = generateData([
"Leonardo",
"Donatello",
"Raphael",
"Michelangelo"
])
Insert cell
stacked = stack(data)
Insert cell
stack = d3.stack()
.offset(d3.stackOffsetWiggle)
.keys(data.keys)
Insert cell
xValue = d => d.time
Insert cell
xScale = d3.scaleLinear()
.domain(d3.extent(data, d => xValue(d)))
.range([0, chartwidth])
Insert cell
yScale = d3.scaleLinear()
.domain([
d3.min(stacked[0], d => d[0]),
d3.max(stacked[stacked.length - 1], d => d[1])
])
.range([chartheight, 0])
Insert cell
colorScale = d3.scaleOrdinal()
.domain(data.keys)
.range(d3.schemeCategory10)
Insert cell
area = d3.area()
.x(d => xScale(xValue(d.data)))
.y0(d => yScale(d[0]))
.y1(d => yScale(d[1]))
.curve(d3.curveBasis)
Insert cell
generateData = keys => {
const n = 100;
const prev = {};
const velocity = {};
const data = d3.range(n).map((d, i) => {
const row = { time: i };
keys.forEach(key => {
velocity[key] = ((velocity[key] || 0) + (Math.random() - .5)) * 0.9;
const value = Math.max(0.2, (prev[key] || Math.random() * 10) + velocity[key]);
prev[key] = row[key] = value;
})
return row;
})
data.keys = keys;
return data;
}
Insert cell
margin = ({left: 0, right: 0, top: 0, bottom: 0})
Insert cell
chartwidth = width - margin.right - margin.left
Insert cell
chartheight = 500 - margin.top - margin.bottom
Insert cell
d3 = require("d3@7", "d3-area-label@1")
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