d3.js将圆焦点添加到多行系列中

时间:2017-03-24 13:03:41

标签: arrays d3.js dataset

经过6个小时后,我设法在我之前的帖子(D3 tooltip show values from nested dataset)中添加了一些关于使用工具提示的文章。

现在我陷入了不同的境界 - 我无法制作与线点对齐的圆点。其他用户已经向我指出了一些方向(感谢@Mark),但仍然无法将所有内容组合在一起并使其按照我的意愿运行。

我为每一行创建了一个圆圈,并带有相应的线条颜色。当用鼠标悬停时,带有所有行的工具提示'出现值,圆圈必须位于x和y轴的线上。

我的问题在于以下一段代码,位于mousemove函数内部,在这个小提琴编辑的第106行:更新的小提琴(https://jsfiddle.net/2en21Lqh/13/):

d3.selectAll(parent + ' .d3-focuspoint')
  .classed("hidden", false)
  .attr("cx", xz(lastDate))
  .attr("cy", function(c) { 
    return d3.map(c.values, function(d,i) {
      if (lastDate == d.date) {
        console.log(d.value);
        return d.value;
      }
   })
});

圈子已经绑定到现有数据(两天前我不会自己想出来的! - 至少我是 sligthly 改进!:/),所以我我试图应用正确的cy值,但无法弄清楚如何做到这一点。 cy内部的函数返回一个对象而不是我正在寻找的d.value。我究竟做错了什么?我已经花了好几个小时找到任何类似的例子,但找不到任何:/

编辑:即使是指向正确方向的指针也会有所帮助:/

1 个答案:

答案 0 :(得分:1)

试试这个:

var mousemoveFunc = function(d, i) {

  var x0 = xz.invert(d3.mouse(this)[0]);

  var lastDate,
      cys = [], //<-- create array to hold y values for circles
      ds = []; //<-- create array to hold tooltip text

  dataGroup.forEach(function(e) { //<-- loop the data (I removed the map since we now need to return two things)
    var i = bisectDate(e.values, x0, 1),
        d0 = e.values[i - 1],
        d1 = e.values[i];

    var d = x0 - d0.date > d1.date - x0 ? d1 : d0;

    lastDate = d.date; //<-- hold onto the date (same for all xs)
    cys.push(d.value); //<-- hold onto the y value for all circles
    ds.push(e.key + " " + d.value); //<-- make the tooltip line
  });

  var mouse = d3.mouse(svg.node()).map(function(d) {
    return parseInt(d);
  });
  var left = Math.min(containerwidth, mouse[0]+margin.left+margin.right),
      top = Math.min(containerheight, mouse[1]+margin.top+margin.right);

  d3.selectAll(parent + ' .d3-focuspoint')
    .classed("hidden", false)
    .attr("cx", xz(lastDate)) //<-- set x position
    .attr("cy", function(d,i) {        
        return yz(cys[i]); //<-- loop the 3 circles and set y position
  });

  tooltip
    .html(lastDate.toString() + "<br/>" + ds.join("<br/>"))
    .classed('hidden', false)
    .style('left', left + 'px')
    .style('top', top + 'px');          

};

更新了fiddle