Published
Edited
Feb 20, 2020
9 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
async function injuriesChart(injuries) {
return vl.markLine()
.data(injuries.flatMap(d => [
{date: d.year_month, subject: "all persons", injury_rate: d.persons_injured / d.incidents},
{date: d.year_month, subject: "pedestrians", injury_rate: d.pedestrian_injured / d.incidents},
{date: d.year_month, subject: "cyclists", injury_rate: d.cyclist_injured / d.incidents},
{date: d.year_month, subject: "motorists", injury_rate: d.motorist_injured / d.incidents}
]))
.encode(
vl.x().fieldT("date").axis({title: false, tickCount: 10}),
vl.y().fieldQ("injury_rate").scale({domain: [0, 1.6]}).axis({title: false}),
vl.color().fieldN("subject")
)
.width(width)
.autosize({type: "fit-x", contains: "padding"})
.render();
}
Insert cell
async function injuries({where = `TRUE`} = {}) {
return queryRows(`SELECT
COALESCE(a.count, 0) AS incidents,
COALESCE(a.number_of_persons_injured, 0) AS persons_injured,
COALESCE(a.number_of_pedestrian_injured, 0) AS pedestrian_injured,
COALESCE(a.number_of_cyclist_injured, 0) AS cyclist_injured,
COALESCE(a.number_of_motorist_injured, 0) AS motorist_injured,
c.year_month AS year_month
FROM (SELECT GENERATE_SERIES('2011-08-01'::TIMESTAMP, '2020-01-01'::TIMESTAMP, '1 month'::INTERVAL) AS year_month) c
LEFT JOIN (
SELECT
COUNT(*) AS count,
SUM(number_of_persons_injured) AS number_of_persons_injured,
SUM(number_of_pedestrian_injured) AS number_of_pedestrian_injured,
SUM(number_of_cyclist_injured) AS number_of_cyclist_injured,
SUM(number_of_motorist_injured) AS number_of_motorist_injured,
TO_TIMESTAMP(year || '-' || LPAD(month::text, 2, '0'), 'YYYY-MM') AS year_month
FROM crashes_all_prod
WHERE
number_of_persons_injured > 0
AND (${where})
GROUP BY year_month
) a ON (a.year_month = c.year_month)
ORDER BY c.year_month
`)
}
Insert cell
async function query(q) {
const response = await fetch(`https://chekpeds.carto.com/api/v2/sql?q=${encodeURIComponent(q)}`);
if (!response.ok) throw new Error(response.status);
return coerceRows(await response.json());
}
Insert cell
async function queryRows(q) {
return (await query(q)).rows;
}
Insert cell
function coerceRows(result) {
const {fields, rows} = result;
for (let name in fields) {
if (fields[name].type === "date") {
for (const row of rows) {
if (row[name] !== null) {
row[name] = new Date(row[name]);
}
}
}
}
return result;
}
Insert cell
import {vl} from "@vega/vega-lite-api"
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