简体   繁体   中英

on mouseover function not executing for d3 line chart

I am trying to implement something similar to this, when mousing over a particular circle representing a data point, show a tooltip with its data: http://bl.ocks.org/d3noob/a22c42db65eb00d4e369

However, I have multiple lines instead of just one line.

Currently, I have made the circles using this using each line's individual dataset, but it seems like when I mouseover the particular circle, there is no mouseover event. Tried console logging but nothing appears too.

svg.selectAll(".dot")
    .data(dataset)
    .enter()
    .append("circle")
    .attr("class", "dot")
    .attr("fill", colors[0])
    .attr("cx", function(d, i) { return x(d.year) })
    .attr("cy", function(d) { return y(d["less than 7"]) })
    .attr("r", 5)
    .on("mouseover", function(d) {
      // console.log("index", i);
      // console.log(d[i]["less than 7"]);
      // div.html(d[i]["less than 7"])
      // .style("left", (d3.event.pageX) + "px")
      // .style("top", (d3.event.pageY) + "px")
      // .style("opacity", 1);
    })
    .on("mouseout", function(d) {
      div.transition()
      .duration(500)
      .style("opacity", 0);
    })

The error console is giving you several useful errors with your code.

div is undefined. You are using it like a variable, but you never define it anywhere. I think you want tooltip.html not div.html . You may want to select the div within tooltip -- not sure.

Also you are trying to access your data with d[i]["less than 7"] . You should write d to the console, because it doesn't appear to be an array at this point. I think you want d["less than 7"] .

Doing this gets the tooltips to work for me:

.on("mouseover", function(d, i) {
  console.log("index", i, d);
  console.log(d["8 to 14 years"]);
  dotTooltip.html(d["8 to 14 years"])
  .style("left", (d3.event.pageX) + "px")
  .style("top", (d3.event.pageY) + "px")
  .style("opacity", 1)
})

The graph in your Plunker, however, is only showing a line along the x-axis for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM