Public
Edited
Apr 11
Insert cell
Insert cell
dataset
Insert cell
multilines = FileAttachment("multilines.png").image()
Insert cell
Insert cell
boroughToMonthToInjuries = d3.rollups(
dataset,
// para todas las colisiones que ocurren en el mismo distrito y mes,
// obtener la suma del número de personas heridas
colisiones => d3.sum(colisiones, c => c.injured),
// agrupar por distrito (borough)
d => d.borough,
// luego agrupar por mes
// d3.timeMonth redondea la fecha hacia abajo al primer día del mes
d => d3.timeMonth(d.date)
)

Insert cell
Insert cell
dataByBorough = boroughToMonthToInjuries
.map(([borough, months]) => ({
borough: borough,
counts: months
.map(([date, injuries]) => ({date, injuries}))
.sort((a, b) => d3.ascending(a.date, b.date))
}))
Insert cell
Insert cell
margin = ({top: 30, right: 30, bottom: 20, left: 40})
Insert cell
width
Insert cell
height = 500
Insert cell
Insert cell
monthExtent = [dataByBorough[0].counts]
Insert cell
monthExtent[0][0]
Insert cell
firstMonth = monthExtent[0][0]["date"]
Insert cell
lastMonth = monthExtent[0][11]["date"]
Insert cell
x = d3.scaleTime()
.domain([firstMonth, lastMonth])
.range([])
Insert cell
Insert cell
maxInjuries = d3.max(dataByBorough, d => d3.max(d.counts, a => a.injuries) )
Insert cell
y = d3.scaleLinear()
.domain([0, maxInjuries]).nice()
.range()
Insert cell
Insert cell
boroughs = []
Insert cell
color = d3.scaleOrdinal()
.domain()
.range()
Insert cell
Insert cell
dataByBorough[0].counts[0]
Insert cell
line = d3.line()
.x(d => )
.y(d => )
Insert cell
Insert cell
line(dataByBorough[0].counts)
Insert cell
Insert cell
xAxis = d3.axisBottom(x)
// mostrar todo el nombre del mes
.tickFormat(d3.timeFormat('%B'))
Insert cell
yAxis = d3.axisLeft(y)
Insert cell
Insert cell
{
const svg = d3.create('svg')
.attr('width', width)
.attr('height', height);

// dibujar los ejes
svg.append('g')
.attr('transform', `translate(0,${height - margin.bottom})`)
.call(xAxis);

svg.append('g')
.attr('transform', `translate(${margin.left})`)
.call(yAxis)
.call(g => g.select('.domain').remove())
// agregar una etiqueta al eje y
.append('text')
.attr('fill', 'black')
.attr('text-anchor', 'start')
.attr('dominant-baseline', 'hanging')
.attr('font-weight', 'bold')
.attr('y', 5)
.attr('x', 0)
.text('Heridos por colisión, 2019');

/* Dibujar las líneas dentro del grupo linesGroup

- Crear un <path> para cada elemento en dataByBorough.
- Usar el generador de líneas para definir el atributo "d".
- Usar la escala de colores para definir el "stroke" (color de línea).
- Definir el "fill" como none (sin relleno).
- Definir el "stroke-width" en 2 (grosor de la línea).
Cuando estés definiendo los atributos con:
.attr('foo', d => ...)
recuerda que "d" es un objeto que se ve así:
{
borough: "BROOKLYN",
counts: [
{date: 2019-01-01T00:00, injuries: 968},
{date: 2019-02-01T00:00, injuries: 857},
...
]
}
*/

const linesGroup = svg.append('g');

return svg.node();
}

Insert cell
Insert cell
areachart = FileAttachment("areachart.png").image()
Insert cell
Insert cell
injuriesByMonthAndBorough = d3.rollup(
dataset,
// 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
Array.from(injuriesByMonthAndBorough)[0]
Insert cell
Insert cell
stack = d3.stack()
.keys(boroughs)
// define how to get the value for a given borough
.value(([month, boroughtToCount], borough) => boroughtToCount.get(borough))
.order(d3.stackOrderDescending)
// .offset(d3.stackOffsetExpand)
Insert cell
Insert cell
stacked = stack(injuriesByMonthAndBorough)
Insert cell
Insert cell
stacked[1][0]
Insert cell
Insert cell
myArray = {
const numbers = [1, 2, 3];
numbers.message = "hello";
return numbers;
}
Insert cell
myArray[0]
Insert cell
myArray.message
Insert cell
Insert cell
stacked[1]
Insert cell
stacked[1].key
Insert cell
Insert cell
stacked[1][0]
Insert cell
stacked[1][0].data
Insert cell
Insert cell
margin
Insert cell
width
Insert cell
height
Insert cell
Insert cell
x
Insert cell
color
Insert cell
Insert cell
injuriesByMonthAndBorough
Insert cell
stacked
Insert cell
maxTotalInjuries = 0
Insert cell
yStacked = d3.scaleLinear()
.domain().nice()
.range()
Insert cell
Insert cell
stacked[1][0]
Insert cell
area = d3.area()
.x(d => )
.y1(d => )
.y0(d => )
Insert cell
Insert cell
{

const svg = d3.create('svg')
.attr('width', width)
.attr('height', height);


const xAxis = d3.axisBottom(x).tickFormat(d3.timeFormat('%B')); // formato con nombre del mes

const yAxis = d3.axisLeft(yStacked);

svg.append('g')
.attr('transform', `translate(0,${height - margin.bottom})`)
.call(xAxis)
.call(g => g.selectAll('.domain').remove());

svg.append('g')
.attr('transform', `translate(${margin.left})`)
.call(yAxis)
.call(g => g.selectAll('.domain').remove())
.append('text')
.attr('fill', 'black')
.attr('text-anchor', 'start')
.attr('dominant-baseline', 'hanging')
.attr('font-weight', 'bold')
.attr('y', 5)
.attr('x', 0)
.text('Heridos por colisión, 2019');

/* Dibujar las áreas dentro del grupo areasGroup.
Crear un <path> para cada elemento en "stacked".
- Usar el generador de áreas para definir el atributo "d".
- Usar la escala de colores para definir el "fill".

Cuando estés definiendo los atributos con:
.attr('foo', d => ...)
recuerda que "d" es el array de datos de una capa.
El *borough* correspondiente a esa capa está en d.key
*/

const areasGroup = svg.append('g');

return svg.node();
}

Insert cell
Insert cell
d3 = require('d3@7')
Insert cell
dataset = (await d3.csv(url, crash => ({
date: d3.timeParse('%m/%d/%Y')(crash.date),
borough: crash.borough,
injured: +crash.injured,
}))).filter(d => d.borough !== '' && d.injured >= 1)
Insert cell
url = 'https://gist.githubusercontent.com/DanielKerrigan/d01fc44e4cee0c5c2434f464497ba260/raw/982bcefac49be9fd29887cbaead524e033f6dad4/nyc-collisions-2019-reduced.csv'
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