Published
Edited
Oct 23, 2020
6 forks
Importers
10 stars
Insert cell
Insert cell
chart = {
const svg = d3.select(DOM.svg(width, h))
.classed("crashes-heatmap", true)
// code credit: https://observablehq.com/@tmcw/d3-scalesequential-continuous-color-legend-example
// and: https://www.visualcinnamon.com/2016/05/smooth-color-legend-d3-svg-gradient.html
const defs = svg.append("defs");
const linearGradient = defs.append("linearGradient")
.attr("id", "linear-gradient");
linearGradient.selectAll("stop")
.data(color.ticks().map((t, i, n) => ({ offset: `${100*i/n.length}%`, color: color(t) })))
.enter().append("stop")
.attr("offset", d => d.offset)
.attr("stop-color", d => d.color);
const g = svg.append("g")
.attr("transform", `translate(${margin.left}, ${margin.top})`)
g.selectAll("rect")
.data(data)
.enter().append("rect")
.attr("x", d => d.hour * gridSize)
.attr("y", d => d.day * gridSize)
.attr("width", gridSize)
.attr("height", gridSize)
.attr("fill", d => color(d.value))
.attr("stroke", "#e2e2e2")
.append("title")
.text(d => d.value)
g.selectAll(".day")
.data(days)
.enter().append("text")
.text(d => d)
.classed("day", true)
.attr("x", 0)
.attr("y", (d, i) => i * gridSize)
.style("text-anchor", "end")
.attr("transform", "translate(-6," + gridSize / 1.5 + ")")
g.selectAll(".hour")
.data(hours)
.enter().append("text")
.text(d => d)
.classed("hour", true)
.attr("x", (d, i) => i * gridSize)
.attr("y", 0)
.style("text-anchor", "middle")
.attr("transform", "translate(" + gridSize / 2 + ", -6)");
g.append("g")
.call(legend)
return svg.node();
}
Insert cell
margin = ({ top: 40, right: 50, bottom: 70, left: 50 })
Insert cell
w = width - margin.left - margin.right
Insert cell
gridSize = Math.floor(w / hours.length )
Insert cell
h = gridSize * days.length + margin.top + margin.bottom
Insert cell
days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
Insert cell
hours = d3.range(24)
Insert cell
color = d3
.scaleSequential()
.domain([0, d3.max(data, d => d.value)])
.interpolator(t => d3.interpolateViridis(1 - t)) // reverses the color ramp
Insert cell
legend = g => {
g.attr("transform", `translate(0, ${h - margin.bottom - legendBarHeight })`)
.append("rect")
.attr("width", w)
.attr("height", legendBarHeight)
.style("fill", "url(#linear-gradient)")
g.call(axisBottom)
}
Insert cell
axisScale = d3.scaleLinear()
.domain(color.domain())
.range([0, w])
Insert cell
axisBottom = g => {
g.classed("axis axis--bottom", true)
.attr("transform", `translate(0, ${h - margin.bottom - legendBarHeight})`)
.call(d3.axisBottom(axisScale)
.ticks(width / 80)
.tickSize(legendBarHeight))
.select(".domain")
.remove()
}
Insert cell
legendBarHeight = 10
Insert cell
css = html`<style>
svg.crashes-heatmap text {
font-family: sans-serif;
font-size: 12px;
fill: #333;
}

svg.crashes-heatmap .axis.axis--bottom line {
stroke: #fff;
}
</style>`
Insert cell
Insert cell
query = sls`
SELECT
EXTRACT(HOUR FROM c.date_val) as hour,
EXTRACT(DOW FROM c.date_val) as day,
c.number_of_persons_injured as value
FROM crashes_all_prod c
WHERE
( year::text || LPAD(month::text, 2, '0') <= '2019' || LPAD(3::text, 2, '0') ) AND
( year::text || LPAD(month::text, 2, '0') >= '2019' || LPAD(1::text, 2, '0') ) AND
( number_of_persons_injured > 0 )
GROUP BY hour, day, value
ORDER BY day, hour, value
`
Insert cell
url = `https://chekpeds.carto.com/api/v2/sql?q=${encodeURIComponent(query)}&format=CSV`
Insert cell
data = {
try {
return await d3.csv(url, parseRow);
} catch (e) {
throw new Error(`Something went wrong: ${e.message}`)
}
}
Insert cell
parseRow = d => {
Object.keys(d).forEach(key => d[key] = +d[key])
return d;
}
Insert cell
Insert cell
d3 = require("d3@5")
Insert cell
sls = require('https://bundle.run/single-line-string@0.0.2')
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more