Published
Edited
Nov 18, 2020
1 fork
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
chart = {
//create SVG container
let svg = d3.create("svg").attr("viewBox", [0, 0, width, height]);

//make a group, and add all paths
svg
.append("g")
.selectAll("path")
.data(series)
.join("path")
.attr("fill", d => color(d))
.attr("d", area)
.append("title")
.text(({ key }) => key);

//add axes to plot
svg.append("g").call(xAxis);
svg.append("g").call(yAxis);

return svg.node();
}
Insert cell
Insert cell
import { data } from '@yuanyuanhu96/inc5000'
Insert cell
Insert cell
data
Insert cell
Insert cell
industries = {
let indCol = [];
data.series.forEach(function(ind) {
indCol.push(ind.name);
});
return indCol;
}
Insert cell
Insert cell
years = {
return data.dates;
}
Insert cell
Insert cell
yearlyIndustries = {
//grab all the industries yearly data
let yI = [];
data.series.forEach(function(ind) {
yI.push(ind.values);
});

//flip rows and columns so the data is sorted by year
yI = d3.transpose(yI);

let yM = [];

//convert to object so that each year has named properties for each industry
yI.forEach(function(y, i) {
let collector = {};
collector.date = years[i];

y.forEach(function(z, j) {
collector[industries[j]] = z;
});
yM.push(collector);
});

return yM;
}
Insert cell
Insert cell
series = d3.stack().keys(industries)(yearlyIndustries)
Insert cell
Insert cell
area = d3
.area()
.x(d => x(d.data.date))
.y0(d => y(d[0]))
.y1(d => y(d[1]))
Insert cell
Insert cell
x = d3
.scaleLinear()
.domain(d3.extent(years, d => d))
.range([margin.left, width - margin.right])
Insert cell
Insert cell
y = d3
.scaleLinear()
.domain([0, d3.max(series, d => d3.max(d, d => d[1]))])
.nice()
.range([height - margin.bottom, margin.top])
Insert cell
Insert cell
//https://observablehq.com/@d3/color-schemes

color = d3
.scaleOrdinal()
.domain(industries)
.range(d3.schemeTableau10)
Insert cell
Insert cell
xAxis = g =>
g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x).tickFormat(d => d))
Insert cell
Insert cell
yAxis = g =>
g.attr("transform", `translate(${margin.left},0)`).call(d3.axisLeft(y))
Insert cell
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