Published
Edited
May 16, 2020
Insert cell
Insert cell
map = {
let map = d3
.create("svg")
.attr("width", map_width)
.attr("height", map_height);

let group = map
.append("g")
.selectAll('path')
.data(districts.features)
.enter()
.append('path')
.attr('d', geoGenerator)
.style('stroke', 'white')
.style('stroke-width', '1px')
.style('fill', color)
.attr('title', function(d) {
let elected = d.properties.election_data.filter(
d => d.elected_flag == 'Y'
)[0];
return `
${d.properties.name}, ${d.properties.province}
<br />
${elected.candidate}, ${elected.party}`;
})
.on('mouseenter', function() {
map.selectAll('path').attr('opacity', 0.3);
d3.select(this).attr('opacity', 1);
})
.on('mouseleave', function() {
map.selectAll('path').attr('opacity', 1);
});

group.nodes().forEach(d => tippy(d, { followCursor: true }));

return map.node();
}
Insert cell
geoGenerator = d3.geoPath().projection(
d3
.geoIdentity()
.reflectY(true)
.fitSize([map_width, map_height], districts)
)
Insert cell
map_height = 0.8 * map_width
Insert cell
map_width = 0.9 * width
Insert cell
// All the winning districts
new Set(
districts.features.map(function(d) {
let elected = d.properties.election_data.filter(d => d.elected_flag == 'Y');
return elected[0].party;
})
)
Insert cell
function color(district) {
let winning_party;
let elected = district.properties.election_data.filter(
d => d.elected_flag == 'Y'
);
if (elected.length == 1) {
winning_party = elected[0].party;
if (winning_party == "NDP-New Democratic Party") {
return d3.schemeCategory10[1];
} else if (winning_party == "Conservative") {
return d3.schemeCategory10[0];
} else if (winning_party == "Liberal") {
return d3.schemeCategory10[3];
} else if (winning_party == "Bloc Québécois") {
return d3.schemeCategory10[9];
} else if (winning_party == "Green Party") {
return d3.schemeCategory10[2];
}
}
return 'gray';
}
Insert cell
districts = topojson.feature(ce, ce.objects.canadian_elections2)
Insert cell
ce = FileAttachment('canadian_elections_topo.json').json()
Insert cell
topojson = require("topojson-client@3")
Insert cell
d3 = require('d3@5')
Insert cell
tippy = require("https://unpkg.com/tippy.js@2.5.4/dist/tippy.all.min.js")
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