简体   繁体   中英

Multiline chart d3 tooltip

I am trying to add a tooltip to the multiline chart but I'm unable to format it like the way I wanted. Currently I'm getting tooltip text at the connecting points but I want to get all the point data inside a rect at the top like in the sample image I'm using d3 for the chart. Here's the piece of code on mousemove.

.on('mousemove', function (e) { // mouse moving over canvas
  const mouse = e.clientX;
  d3.select(".mouse-line-" + chart_sel)
    .attr("d", function () {
      var d = "M" + mouse + "," + height;
      d += " " + mouse + "," + 0;
      return d;
    });

  d3.selectAll(".mouse-per-line-" + chart_sel)
    .attr("transform", function (d, i) {
      var xDate = x.invert(mouse),
        bisect = d3.bisector(function (d) { return d.date; }).right;
      idx = bisect(d.values, xDate);
      d3.select(".mouse-line-" + chart_sel)
        .attr("d", function () {
          var data = "M " + x(d.values[idx].date) + "," + (height);
     data += "L " + x(d.values[idx].date) + "," + 0;
          return data;
        });
      var beginning = 0,
        end = lines[i].getTotalLength(),
        target = null;

      while (true) {
        target = Math.floor((beginning + end) / 2);
        pos = lines[i].getPointAtLength(target);
        if ((target === end || target === beginning) && pos.x !== mouse[0]) {
          break;
        }
        if (pos.x > mouse[0]) end = target;
        else if (pos.x < mouse[0]) beginning = target;
        else break; //position found
      }
      d3.select(this).select('text')
        .text(Math.round(y.invert(pos.y)))
        .style("text-anchor", "start")
      return "translate(" + x(d.values[idx].date) + "," + y(d.values[idx].value) + ")";

    });
 })

Here's the link to the code in codepen .

Here's the sample for the tooltip

图片

Thanks in advance!

I found some errors in your pen:

You cannot use d3.pointer(this) in D3.V6. Instead, get the pointer position from the mousemove callback argument:

.on('mousemove', e => {
  const x = e.clientX; // instead of mouse[0]
  ...
}

The path string you format has 'M' (move to) but doen not have 'L' (line to) directive, should be 'M x,y L x,y' :

var data = "M " + x(d.values[idx].date) + "," + (height);
data += "L " + x(d.values[idx].date) + "," + 0;

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