Published
Edited
Dec 30, 2020
Importers
10 stars
Insert cell
Insert cell
Insert cell
chart = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);

svg.append("g")
.selectAll("path")
.data(series)
.join("path")
.attr("fill", ({key}) => color(key))
.attr("d", area)
.append("title")
.text(({key}) => key);

svg.append("g")
.attr("fill", "none")
.attr("stroke", "white")
.selectAll("path")
.data(series)
.join("path")
.attr("d", area.lineY1());

svg.append("g")
.attr("font-size", 10)
.attr("font-family", "sans-serif")
.attr("text-anchor", "middle")
.selectAll("text")
.data(series)
.join("text")
.attr("dy", "0.35em")
.text(d => d.key)
.datum(d => d3.greatest(d, ([a, b]) => b - a))
.attr("text-anchor", d => x(d.data[0]) < 100 ? "start" : x(d.data[0]) > width - 100 ? "end" : null)
.attr("dx", d => x(d.data[0]) < 100 ? "1em" : x(d.data[0]) > width - 100 ? "-1em" : null)
.attr("transform", d => `translate(${x(d.data[0])},${y((d[0] + d[1]) / 2)})`);

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

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

return svg.node();
}
Insert cell
data = FileAttachment("os (1).csv").csv({typed: true})
Insert cell
series = d3.stack()
.keys(d3.group(data, d => d.name).keys())
.value(([, values], name) => values.get(name) || 0)
(d3.rollup(data, ([d]) => d.value, d => +d.date, d => d.name))
Insert cell
area = d3.area()
.x(d => x(d.data[0]))
.y0(d => y(d[0]))
.y1(d => y(d[1]))
Insert cell
x = d3.scaleUtc()
.domain(d3.extent(data, d => d.date))
.rangeRound([margin.left, width - margin.right])
Insert cell
y = d3.scaleLinear()
.domain([0, 100])
.range([height - margin.bottom, margin.top])
Insert cell
color = d3.scaleOrdinal()
.domain(d3.groups(data, d => d.name)
.sort(([, a], [, b]) => d3.descending(d3.sum(a, d => d.value), d3.sum(b, d => d.value)))
.slice(0, 9) // only color the top nine
.sort(([ak, [a]], [bk, [b]]) => d3.ascending(a.date, b.date) || d3.ascending(ak, bk))
.map(([name]) => name))
.range(d3.schemeTableau10)
.unknown(d3.schemeTableau10[9]) // "other"
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))
.call(g => g.select(".domain").remove())
Insert cell
formatDate = d3.utcFormat("%b %Y")
Insert cell
formatValue = d => `${d.toFixed(1)}%`
Insert cell
height = 600
Insert cell
margin = ({top: 20, right: 30, bottom: 30, left: 30})
Insert cell
d3 = require("d3@6")
Insert cell
import {swatches} from "@d3/color-legend"
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