Public
Edited
Apr 24, 2023
1 fork
21 stars
Insert cell
Insert cell
Insert cell
Insert cell
chart = {
const div = html`<div style="position:relative;">`;

const canvas = d3.select(div)
.selectAll("canvas")
.data(data)
.enter().append(() => DOM.context2d(width, step).canvas)
.style("position", "absolute")
.style("top", (d, i) => `${i * (step + 1) + margin.top}px`)
.each(horizon);

const svg = d3.select(div.appendChild(DOM.svg(width, height)))
.style("position", "relative")
.style("font", "10px sans-serif");

svg.append("g")
.call(xAxis);

svg.append("g")
.selectAll("text")
.data(data)
.join("text")
.attr("x", 4)
.attr("y", (d, i) => (i + 0.5) * (step + 1) + margin.top)
.attr("dy", "0.35em")
.text(d => d.key);

function horizon(d) {
const context = this.getContext("2d");
area.context(context);
for (let i = 0; i < overlap; ++i) {
context.save();
context.translate(0, (i + 1) * step);
context.beginPath();
area(d.values);
context.fillStyle = color(i);
context.fill();
context.restore();
}
}

return div;
}
Insert cell
height = data.length * (step + 1) + margin.top + margin.bottom
Insert cell
margin = ({top: 30, right: 10, bottom: 0, left: 10})
Insert cell
step = 23
Insert cell
color = i => d3[scheme][Math.max(3, overlap)][i + Math.max(0, 3 - overlap)]
Insert cell
x = d3.scaleUtc()
.domain([data[0].values[0].date, data[0].values[data[0].values.length - 1].date])
.range([0, width])
Insert cell
y = d3.scaleLinear()
.domain([0, d3.max(data, d => d3.max(d.values, d => d.value))])
.range([0, -overlap * step])
Insert cell
xAxis = g => g
.attr("transform", `translate(0,${margin.top})`)
.call(d3.axisTop(x).ticks(width / 80).tickSizeOuter(0))
.call(g => g.selectAll(".tick").filter(d => x(d) < margin.left || x(d) >= width - margin.right).remove())
.call(g => g.select(".domain").remove())
Insert cell
area = d3.area()
.curve(d3.curveBasis)
.defined(d => !isNaN(d.value))
.x(d => x(d.date))
.y0(0)
.y1(d => y(d.value))
Insert cell
data = d3.groups(d3.csvParse(await FileAttachment("traffic.csv").text(), d3.autoType), d => d.name)
.map(([name, values]) => ({
key: name,
values: values.sort((a, b) => d3.ascending(a.date, b.date)),
sum: d3.sum(values, d => d.value)
}))
.sort((a, b) => d3.descending(a.sum, b.sum))
Insert cell
d3 = require("d3@6")
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