chart = {
const svg = d3.create('svg')
.attr('viewBox', [0, -30, width, height]);
const tooltip = d3
.select("body")
.append("div")
.attr("class", "svg-tooltip")
.style("position", "absolute")
.style("visibility", "hidden")
.style('font-family', 'Helvetica')
.style('background', 'white')
.style('opacity', .9)
.style('border-radius', '.1rem')
.style('border', '0px solid black')
.style('color', 'black')
.style('display', 'block')
.style('font-size', '14px')
.style('max-width', '320px')
.style('padding', '.2rem .4rem')
.style('position', 'absolute');
svg.append('g').call(xAxis);
svg.selectAll('.line-consumption')
.data(x.ticks())
.join('line')
.attr('class', 'line-consumption')
.attr('x1', d => x(d))
.attr('x2', d => x(d))
.attr('y1', 10)
.attr('y2', height - margin.top +35)
.attr('stroke-width', .6)
.attr('stroke', 'lightgray');
svg.selectAll('.label-continents')
.data(continentsArray)
.join('text')
.attr('class', 'label-continents')
.attr('x', 0)
.attr('y', d => y(d))
.style('font-family', 'Helvetica')
.style('font-size', '12px')
.attr('text-align', 'right')
.attr('alignment-baseline', 'right')
.text(d => d);
const simulation = d3.forceSimulation(selectedYear)
.force('x', d3.forceX((d) => x(d.renewablesShareCon)).strength(0.3))
.force('y', d3.forceY((d) => y(d.continent)).strength(0.3))
.force('collide', d3.forceCollide(d => size(d.gdpPerCap)/1.5 + padding).strength(1))
.stop();
for(let i = 0; i < 300; i++) {
simulation.tick();
}
simulation.stop();
svg.selectAll('circle')
.data(selectedYear)
.join('circle')
.attr('cx', d => d.x)
.attr('cy', d => d.y)
.attr('r', d => size(d.gdpPerCap)/1.5)
.attr('fill', d => color(d.continent))
.attr('opacity', .8);
svg.selectAll("circle")
.on("mouseover", function(d) {
d3.select(this)
.attr('stroke-width', '1')
.attr("stroke", "black")
tooltip
.style("visibility", "visible")
.html(`<b>Country:</b> ${d.country} <br><b>GDP per cap: </b>${d.gdpPerCap.toLocaleString('en-US', {maximumFractionDigits: 2})}<br><b>% of primary energy renewables consumption:</b> ${d.renewablesShareCon.toLocaleString('en-US', {maximumFractionDigits: 2})}%`)
})
.on("mousemove", function() {
tooltip
.style("top", d3.event.pageY - 10 + "px")
.style("left", d3.event.pageX + 10 + "px")
})
.on("mouseout", function() {
d3.select(this).attr('stroke-width', '0');
tooltip.style("visibility", "hidden");
});
return svg.node();
}