Published
Edited
Apr 15, 2020
Insert cell
Insert cell
Insert cell
Insert cell
chart(data)
Insert cell
function chart(data) {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height])
.style("font", "10px sans-serif");

const g = svg.append("g")
.selectAll("g")
.data(data.series.map(d => Object.assign({
clipId: DOM.uid("clip"),
pathId: DOM.uid("path")
}, d)))
.join("g")
.attr("transform", (d, i) => `translate(0,${i * (step + 1) + margin.top})`);

g.append("clipPath")
.attr("id", d => d.clipId.id)
.append("rect")
.attr("width", width)
.attr("height", step);

g.append("defs").append("path")
.attr("id", d => d.pathId.id)
.attr("d", d => area(d.values));

g.append("g")
.attr("clip-path", d => d.clipId)
.selectAll("use")
.data(d => new Array(overlap).fill(d))
.join("use")
.attr("fill", (d, i) => color(i))
.attr("transform", (d, i) => `translate(0,${(i + 1) * step})`)
.attr("xlink:href", d => d.pathId.href);

g.append("text")
.attr("x", 4)
.attr("y", step / 2)
.attr("dy", "0.35em")
.text(d => d.name);

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

return svg.node();
}
Insert cell
height = data.series.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(d3.extent(data.dates))
.range([0, width])
Insert cell
y = d3.scaleLinear()
.domain([0, d3.max(data.series, d => d3.max(d.values))])
.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))
.x((d, i) => x(data.dates[i]))
.y0(0)
.y1(d => y(d))
Insert cell
data = {
const data = d3.csvParse(await FileAttachment("traffic.csv").text(), d3.autoType);
const dates = Array.from(d3.group(data, d => +d.date).keys()).sort(d3.ascending);
return {
dates: dates.map(d => new Date(d)),
series: d3.groups(data, d => d.name).map(([name, values]) => {
const value = new Map(values.map(d => [+d.date, d.value]));
return {name, values: dates.map(d => value.get(d))};
})
};
}
Insert cell
d3 = require("d3@5", "d3-array@2")
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