Published
Edited
Apr 2, 2021
Insert cell
Insert cell
chart = {
const width = 975;
const height = 610;

const zoom = d3.zoom()
.scaleExtent([1, 8])
.on("zoom", zoomed);

const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height])
.on("click", reset);

const g = svg.append("g")
.attr("stroke", "blue")
.attr("cursor", "grab");

const states = g.append("g")
.attr("fill", "#444")
.attr("cursor", "pointer")
.selectAll("path")
.data(topojson.feature(us, us.objects.states).features)
.join("path")
.on("click", clicked)
.attr("d", path);
states.append("title")
.text(d => d.properties.name);
g.append("path")
.attr("fill", "none")
.attr("stroke", "white")
.attr("stroke-linejoin", "round")
.attr("d", path(topojson.mesh(us, us.objects.states, (a, b) => a !== b)));
svg.call(zoom);
for (const d of data) {
g.append("circle")
.attr("transform", `translate(${d})`)
.attr("r", 3)
.attr("fill-opacity", 1)
.attr("stroke-opacity", 0)
.transition()
.attr("fill-opacity", 0)
.attr("stroke-opacity", 1);
}

function reset() {
states.transition().style("fill", null);
svg.transition().duration(750).call(
zoom.transform,
d3.zoomIdentity,
d3.zoomTransform(svg.node()).invert([width / 2, height / 2])
);
}

function clicked(event, d) {
const [[x0, y0], [x1, y1]] = path.bounds(d);
event.stopPropagation();
states.transition().style("fill", null);
d3.select(this).transition().style("fill", "red");
svg.transition().duration(750).call(
zoom.transform,
d3.zoomIdentity
.translate(width / 2, height / 2)
.scale(Math.min(8, 0.9 / Math.max((x1 - x0) / width, (y1 - y0) / height)))
.translate(-(x0 + x1) / 2, -(y0 + y1) / 2),
d3.pointer(event, svg.node())
);
}

function zoomed(event) {
const {transform} = event;
g.attr("transform", transform);

}

return svg.node();
}
Insert cell
Insert cell
path = d3.geoPath()
Insert cell
us = FileAttachment("states-albers-10m.json").json()
Insert cell
topojson = require("topojson-client@3")
Insert cell
d3 = require("d3@6")
Insert cell
data = {
const parseDate = d3.timeParse("%m/%d/%Y");
const projection = d3.geoAlbersUsa().scale(1280).translate([480, 300]);
const data = await d3.tsv("https://gist.githubusercontent.com/mbostock/4330486/raw/fe47cd0f43281cae3283a5b397f8f0118262bf55/walmart.tsv", d => {
const p = projection(d);
p.date = parseDate(d.date);
return p;
});
data.sort((a, b) => a.date - b.date);
return data;
}
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