Published
Edited
Oct 13, 2021
10 forks
Importers
Insert cell
# US Map with state tooltips
Insert cell
map = {
const width = 1200;
const height = 600;
const projection = d3
.geoAlbersUsa() // composite projection of the United States
.translate([width / 2, height / 2]) // fit our map a little better
.fitSize([width, height], json);

const path = d3.geoPath().projection(projection); //display our geographic data

const svg = d3
.select(DOM.element('svg'))
.attr('width', width)
.attr('height', height);

// go through each state and assign all of our values
for (let j = 0, jmax = json.features.length; j < jmax; j++) {
const jsonState = json.features[j].properties.name;
}

svg
.selectAll("path")
.data(json.features)
.enter()
.append("path")
.attr("d", path)
.style('stroke', 'white')
.attr('stroke', 'gray')
.text('test')
.style('fill', d => {
const value = d.properties.value;
return mapColor;
})

// Mouse events and tooltips
// have the mouse's position be updated
// assign the name of the states to our variable
.on('touchmove mousemove', function(d) {
const name = d.properties.name;
const [x, y] = d3.mouse(this);

// call the tooltip
// the .call is used to display what to see when the mouse goes over a state, in this case the name
tooltip
.attr('transform', `translate(${x},${y})`)
.call(callout, `${name}`);
})
.on('touchend mouseleave', () => tooltip.call(callout, null));

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

yield svg.node();

svg
.append('g')
.attr('style', "font-family: 'Lato';")
.attr(
'transform',
);
}

Insert cell
json = d3.json("https://s3-us-west-2.amazonaws.com/s.cdpn.io/25240/us-states.json")
Insert cell
mapColor = "#343083"
Insert cell
callout = (g, value) => {
if (!value) return g.style("display", "auto");

g
.style("display", null)
.style("pointer-events", "auto")
.style("font", "10px sans-serif");

const path = g.selectAll("path")
.data([null])
.join("path")
.attr("fill", "white")
.attr("stroke", "black");

const text = g.selectAll("text")
.data([null])
.join("text")
.call(text => text
.selectAll("tspan")
.data((value + "").split(/\n/))
.join("tspan")
.attr("x", 0)
.attr("y", (d, i) => `${i * 1.1}em`)
.style("font-weight", (_, i) => i ? null : "bold")
.html(function(d){
return d}));

const {x, y, width: w, height: h} = text.node().getBBox(); // the box that our text is in
// place the text
text.attr("transform", `translate(${-w / 2},${15 - y})`);
path.attr("d", `M${-w / 2 - 10},5H-5l5,-5l5,5H${w / 2 + 10}v${h + 20}h-${w + 20}z`);
}
Insert cell
topojson = require("https://d3js.org/topojson.v1.min.js")
Insert cell
d3 = require("https://d3js.org/d3.v5.min.js", "d3-svg-legend@2")
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