Published
Edited
Aug 17, 2022
3 forks
Importers
25 stars
Also listed in…
D3 Tutorials
Insert cell
Insert cell
matrixData = groupToStack(data, "year", "gruposdeedad", v =>
d3.sum(v, d => d.total)
)
Insert cell
Insert cell
Insert cell
table(matrixData, {})
Insert cell
Insert cell
table(data, { paged: 10 })
Insert cell
Insert cell
Insert cell
// data = loadSocrata("https://www.datos.gov.co/resource/grgp-6bef.csv")
data = FileAttachment("proyeccionesCensoColombia.csv").csv()
Insert cell
Insert cell
groupedMap = d3.group(
data,
d => d[groupBy],
d => d[stackBy]
)
Insert cell
Insert cell
stackKeys = Array.from(new Set(data.map(d => d[stackBy])).values())
.filter(d => d !== "Total")
.sort((a, b) => +a.split("-")[0] - +b.split("-")[0])
Insert cell
Insert cell
tableData = {
// How we want to aggregate the data
const reducer = v => d3.sum(v, d => d.total);

return Array.from(groupedMap.entries())
.map(g => {
const obj = {};
obj[groupBy] = g[0];
for (let col of stackKeys) {
const vals = g[1].get(col);
obj[col] = !vals ? 0 : reducer(Array.from(vals.values()));
}
return obj;
})
.sort((a, b) => a[groupBy] - b[groupBy]);
}
Insert cell
Insert cell
table(tableData)
Insert cell
Insert cell
stackedData = d3.stack().keys(stackKeys)(tableData)
Insert cell
Insert cell
series = stackedData.map(d => {
d.forEach(v => {
v.key = d.key;
v.data.name = v.data[groupBy];
});

return d;
})
Insert cell
dataForChart = data
.map(d => ((d.name = d[groupBy]), d))
.sort((a, b) => +a[groupBy] - b[groupBy])
Insert cell
import { chart } with {
series,
dataForChart as data,
color
} from "@d3/stacked-bar-chart@538"
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
chart
Insert cell
series
Insert cell
dataForChart
Insert cell
Insert cell
groupToStack = function(data, groupBy, colorBy, reducer = v => v.length) {
const groupedMap = d3.group(data, d => d[groupBy], d => d[colorBy]);

const keys = Array.from(new Set(data.map(d => d[colorBy])).values());

return Array.from(groupedMap.entries()).map(g => {
const obj = {};
obj[groupBy] = g[0];
for (let col of keys) {
const vals = g[1].get(col);
obj[col] = !vals ? 0 : reducer(Array.from(vals.values()));
}
return obj;
});
}
Insert cell
color = d3
.scaleOrdinal()
.domain(series.map(d => d.key))
.range(
d3
.quantize(t => d3.interpolateSpectral(t * 0.8 + 0.1), series.length)
.reverse()
)
.unknown("#ccc")
Insert cell
Insert cell
Insert cell
import { table } from "@john-guerra/tables"
Insert cell
import { loadSocrata } from "@john-guerra/socrata-load-multiples-pages"
Insert cell
import { select } from "@jashkenas/inputs"
Insert cell
import { legend } 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