{
const svg = d3.create("svg").attr("width", width).attr("height", height);
svg
.append("g")
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(xAxis);
svg.append("g").attr("transform", `translate(${margin.left}, 0)`).call(yAxis);
const bubbles = svg
.selectAll("bubbles")
.data(data)
.enter()
.append("circle")
.attr("cx", (d) => xScale(d["Income per person"]))
.attr("cy", (d) => yScale(d["Life expectancy "]))
.attr("r", (d) => radiusScale(d.Population))
.attr("fill", (d) => colorScale(d.region))
.style("fill-opacity", 0.94)
.attr("stroke", "#fff")
.on("mousemove", function (event, d, index) {
tooltip
.style("left", event.pageX + 0 + "px")
.style("top", event.pageY - 52 + "px")
.style("display", "block")
.html(`${d.name}`);
d3.select(this).style("stroke-width", 3).attr("stroke", "#111");
})
.on("mouseout", function () {
tooltip.style("display", "none");
d3.select(this).style("stroke-width", 1).attr("stroke", "#fff");
});
const tooltip = d3.select("body").append("div").attr("class", "tooltip");
const yUnit = svg
.append("text")
.attr("transform", "translate(20," + height / 2 + ") rotate(-90)")
.text("Life expectancy")
.attr("class", "unit");
const xUnit = svg
.append("text")
.attr("transform", `translate(${width / 2}, ${height - 18})`)
.text("GDP per capita")
.attr("class", "unit");
const legendRects = svg
.selectAll("legend-rects")
.data(regionList)
.enter()
.append("rect")
.attr("x", (d, i) => width - margin.right - 80)
.attr("y", (d, i) => height - margin.bottom - 70 - 25 * i)
.attr("width", 12)
.attr("height", 17)
.attr("fill", (d) => colorScale(d));
const legendTexts = svg
.selectAll("legend-texts")
.data(regionList)
.enter()
.append("text")
.attr("x", (d, i) => width - margin.right - 80 + 20)
.attr("y", (d, i) => height - margin.bottom - 70 - 25 * i + 15)
.text((d) => d)
.attr("class", "legend-texts");
return svg.node();
}