I'm trying to have the value of the bar show in a div generated next to my mouse pointer using a tooltip but It's not working out. Something appears in screen, but It's not what I want neither where I want It. I have an event of loading bars which I think might be the responsable of the problem. Style of the div created has position: absolute;
Here's my code:
// set the dimensions and margins of the graph
const margin = {top: 30, right: 30, bottom: 70, left: 150},
width = 660 - margin.left - margin.right,
height = 600 - margin.top - margin.bottom;
// append the svg object to the body of the page
const svga = d3.select("#my_dataviz2")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
// Parse the Data
d3.csv("https://raw.githubusercontent.com/holtzy/data_to_viz/master/Example_dataset/7_OneCatOneNum_header.csv").then( function(data) {
data.sort((a, b) => b.Value - a.Value);
// X axis
const x = d3.scaleBand()
.range([ 0, width ])
.domain(data.map(d => d.Country))
.padding(0.2)
svga.append("g")
.attr("transform", `translate(0, ${height})`)
.call(d3.axisBottom(x))
.attr("class", "x-axis")
.selectAll("text")
.attr("transform", "translate(-10,0)rotate(-45)")
.style("text-anchor", "end");
// Add Y axis
const y = d3.scaleLinear()
.domain([0, 13000])
.range([ height, 0])
svga.append("g")
.call(d3.axisLeft(y))
.attr("class", "y-axis")
.selectAll("text")
.style("text-anchor", "end")
.style("fill", "#D6D6D6"); // Cambiar "path" por "line"
const div = d3.select("body")
.append("div")
.attr("class", "tooltip")
.style("opacity", 0);
// Bars
svga.selectAll("myRect")
.data(data)
.enter()
.append("rect")
.attr("x", d => x(d.Country) )
.attr("y", d => y(0))
.attr("width", x.bandwidth())
.attr("height", height - y(0) )
.attr("fill", "#FFD31E")
.attr("stroke", "#D6D6D6") // Color del borde
.attr("stroke-width", 1) // Ancho del borde
.attr('transform', 'translate(0, 0)')
.on('mouseover', function (d, i) {
d3.select(this).transition()
.duration('50')
.attr("fill", "#FFE476");
div.transition()
.duration(50)
.style("opacity", 1);
div.html(d.Value)
.style("left", (d3.event.pageX + 10) + "px")
.style("top", (d3.event.pageY - 15) + "px");
})
.on('mouseout', function (d, i) {
d3.select(this).transition()
.duration('50')
.attr("fill", "#FFD31E")
div.transition()
.duration('50')
.style("opacity", 0)
})
svga.selectAll("rect")
.transition()
.duration(600)
.attr("y", d => y(d.Value))
.attr("height", d => height - y(d.Value))
.delay((d, i) => i * 100);
})
I think the bar loading event is messing It up.