this is my first time asking a question here so bear with me, please.
I’m trying to add a tooltip for my scatterplot but it always ends up outside of my chart, like so:
Image
As you can see, the tooltip is on the left side of the chart.
Here’s my code:
var tooltip = d3.select("#chart-area")
.append("div")
.attr("class", "tooltip")
.style("opacity", 0)
svg.append("g")
.selectAll(".my-circle")
.data(data)
.join("circle")
.attr("class", "my-circle")
.attr("cx", d => xScale(d.Gdp_per_capita) )
.attr("cy", d => yScale(d.Renewable_energy_share_in_primary_energy_consumption_per_capita) )
.attr("r", d => rScale(d.Primary_energy_consumption_per_capita) )
.style("fill", d => colorScale(d.Entity))
.style("fill-opacity", 0.7)
.on("mouseover", function(e, d) {
d3.select('.tooltip')
tooltip
.transition()
.duration(200)
.style("opacity", .9);
tooltip
.html("Country: " + d.Entity)
.style("left", d3.select(this).attr("cx") + "px")
.style("top", d3.select(this).attr("cy") + "px")
})
.on("mouseout", function(e, d) {
tooltip
.transition()
.duration(500)
.style("opacity", 0);
})
And just in case, here’s the code for when I created the SVG:
const margin = {top: 10, right: 30, bottom: 30, left: 60}
const height = 400 - margin.right - margin.left;
const width = 400 - margin.top - margin.bottom;
var svg = d3.select("#chart-area")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom + 30)
.attr("transform", "translate(" + 120 + "," + margin.top + ")")
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
I tried using d3.event.pageX
instead of d3.select(this).attr("cx")
as well as their Y counterparts but it also ends up the same way, except the position of the tooltip doesn’t change at all for each circle.
Image
Wan Izz Naeem Wan Ismail is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.