{
const svg = d3.create('svg')
.attr('width', dimensions.width)
.attr('height', dimensions.height);
svg.append('g')
.attr('transform', `translate(0, ${dimensions.height - dimensions.margin.bottom})`)
.call(d3.axisBottom(x))
.append('text')
.attr('text-anchor', 'end')
.attr('fill', 'black')
.attr('font-size', '12px')
.attr('font-weight', 'bold')
.attr('x', dimensions.width - dimensions.margin.right)
.attr('y', -10)
.text('Fertility');
svg.append('g')
.attr('transform', `translate(${dimensions.margin.left}, 0)`)
.call(d3.axisLeft(y))
.append('text')
.attr('transform', `translate(20, ${dimensions.margin.top}) rotate(-90)`)
.attr('text-anchor', 'end')
.attr('fill', 'black')
.attr('font-size', '12px')
.attr('font-weight', 'bold')
.text('Life Expectancy');
const yearLabel = svg.append('text')
.attr('id', 'yearLabel')
.attr('x', 40)
.attr('y', dimensions.height - dimensions.margin.bottom - 20)
.attr('fill', '#ccc')
.attr('font-family', 'Helvetica Neue, Arial')
.attr('font-weight', 500)
.attr('font-size', 80)
.text("1955");
const legend = svg.append('g')
.attr('transform', `translate(${dimensions.width - 160}, ${dimensions.margin.top})`)
.call(colorLegend); // <-- legend helper is included in Utilities section
const countries = svg.append("g")
.attr("id", "countryGroup")
.selectAll('circle')
.data(dataInitial, d => d.country)
.join('circle')
.sort((a, b) => b.pop - a.pop) // sort so smaller circles are drawn last and won't be blocked by larger circles
.attr("class", "countryCircles") // give these circles a class so we can select them by this class
.attr('opacity', 0.75)
.attr('fill', d => color(d.cluster))
.attr('cx', d => x(d.fertility))
.attr('cy', d => y(d.life_expect))
.attr('r', d => size(d.pop))
/****** show tooltip and border when hovered over ******/
.on("mouseover", function (event, d) { // <-- need to use the regular function definition to have access to "this"
svg.select("#tooltip-text")
.text(d.country);
let positionOffest = 8;
svg.select("#tooltip")
// move the tooltip to where the cursor is
.attr("transform", `translate(${x(d.fertility) + positionOffest}, ${y(d.life_expect) + positionOffest})`)
.style("display", "block"); // make tooltip visible
d3.select(this)
.attr("stroke", "#333333")
.attr("stroke-width", 2);
})
.on("mouseout", function (event, d) {
svg.select("#tooltip").style("display", "none"); // hide tooltip
d3.select(this).attr("stroke", "none"); // undo the stroke
});
/****** Tooltip Code ******/
const tooltipGroup = svg.append("g") // the tooltip needs to be added last so that it stays on top of all circles
.attr("id", "tooltip")
.style("display", "none") // hidden by default
.append("text")
.attr("id", "tooltip-text")
.attr("x", 5)
.attr("y", 15)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "black");
return svg.node();
}