Published
Edited
May 23, 2021
Insert cell
Insert cell
dataset
Insert cell
Insert cell
monthToBoroughToInjuries = d3.rollup(
dataset,
// update this line to get the total number of injuries in the collisions array
collisions => d3.sum(collisions, d => d.injured),
// group by month first
d => d3.timeMonth(d.date),
// then by borough
d => d.borough
)
Insert cell
Insert cell
dataByMonth = Array.from(monthToBoroughToInjuries, (([date, boroughToCount]) => {
const map = Object.fromEntries(boroughToCount);
map['total'] = d3.sum(boroughToCount.values());
map['month'] = date;
return map;
}))
Insert cell
Insert cell
boroughs = Array.from(new Set(dataset.map(d => d.borough)))
Insert cell
Insert cell
stack = d3.stack()
.keys(boroughs)
.order(d3.stackOrderDescending)
// .offset(d3.stackOffsetExpand)
Insert cell
stacked = stack(dataByMonth)
Insert cell
Insert cell
margin = ({top: 10, right: 30, bottom: 20, left: 120})
Insert cell
visWidth = width - margin.left - margin.right
Insert cell
visHeight = 500 - margin.top - margin.bottom
Insert cell
Insert cell
x = d3.scaleTime()
.domain(d3.extent(dataByMonth, d => d.month))
.range([0, visWidth])
Insert cell
y = d3.scaleLinear()
.domain([0, d3.max(dataByMonth, d => d.total)]).nice()
.range([visHeight, 0])
Insert cell
color = d3.scaleOrdinal()
.domain(boroughs)
.range(d3.schemeTableau10)
Insert cell
Insert cell
stacked[1][0]
Insert cell
area = d3.area()
.x(d => x(d.data.month))
.y1(d => y(d[1]))
.y0(d => y(d[0]))
Insert cell
Insert cell
Insert cell
{
// set up
const svg = d3.create('svg')
.attr('width', visWidth + margin.left + margin.right)
.attr('height', visHeight + margin.top + margin.bottom);
const g = svg.append('g')
.attr('transform', `translate(${margin.left}, ${margin.top})`);
// axes
const xAxis = d3.axisBottom(x).tickFormat(d3.timeFormat('%B'))
const yAxis = d3.axisLeft(y);
g.append('g')
.attr('transform', `translate(0,${visHeight})`)
.call(xAxis)
.call(g => g.selectAll('.domain').remove());
g.append('g')
.call(yAxis)
.call(g => g.selectAll('.domain').remove())
.append('text')
.attr('fill', 'black')
.attr('x', -40)
.attr('y', visHeight / 2)
.text('Injured Count');
// areas
g.append('g')
.selectAll('g')
.data(stacked)
.join('g')
.attr('fill', d => color(d.key))
.append('path')
.attr('d', area);
return svg.node();
}
Insert cell
Insert cell
Insert cell
Insert cell
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