Published
Edited
Oct 11, 2018
Insert cell
Insert cell
chart = {
const svg = d3.select(DOM.svg(width, height));

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

svg.append("g")
.call(yAxis);
const serie = svg.append("g")
.selectAll("g")
.data(series)
.enter().append("g")
.attr("transform", d => `translate(0,${y(d.key) + 1})`);
serie.append("path")
.attr("fill", "#ddd")
.attr("d", d => area(d.values));
serie.append("path")
.attr("fill", "none")
.attr("stroke", "black")
.attr("d", d => line(d.values));
return svg.node();
}
Insert cell
overlap = 8
Insert cell
height = series.length * 17
Insert cell
margin = ({top: 40, right: 20, bottom: 30, left: 120})
Insert cell
x = d3.scaleTime()
.domain(d3.extent(data, d => d.date))
.range([margin.left, width - margin.right])
Insert cell
y = d3.scalePoint()
.domain(series.map(d => d.key))
.range([margin.top, height - margin.bottom])
Insert cell
z = d3.scaleLinear()
.domain([0, d3.max(data, d => d.value)]).nice()
.range([0, -overlap * y.step()])
Insert cell
xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x)
.ticks(width / 80)
.tickSizeOuter(0))
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y).tickSize(0).tickPadding(4))
.call(g => g.select(".domain").remove())
.call(g => g.select(".tick:last-of-type text").clone()
.attr("x", 3)
.attr("text-anchor", "start")
.attr("font-weight", "bold")
.text(data.y))
Insert cell
area = d3.area()
.curve(d3.curveBasis)
.defined(d => !isNaN(d.value))
.x(d => x(d.date))
.y0(0)
.y1(d => z(d.value))
Insert cell
line = area.lineY1()
Insert cell
series = d3.nest()
.key(d => d.name)
.sortValues((a, b) => a.date - b.date)
.entries(data)
Insert cell
data = d3.csv("https://gist.githubusercontent.com/chrtze/c74efb46cadb6a908bbbf5227934bfea/raw/c32d94689dd432609c55d1758d8e69c59f94f802/traffic_weekly.csv", ({name, date, total_1, total_2}) => ({name, date: new Date(date * 1000), value: +total_1 + +total_2}))
Insert cell
d3 = require("d3@5")
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