使用D3 JavaScript向数组中的圆圈添加工具提示

时间:2015-07-04 09:38:15

标签: javascript d3.js tooltip

我试图像this example中那样向圆圈添加工具提示。这是我的DEMO

我试图在此方法中显示工具提示中的数组值,但工具提示不会显示在图表上:

function plotMeans(){
    var circle = svg.selectAll("circle.means")
            .data(numeric.transpose([x_means, y_means]));

    var tip = d3.tip()
            .attr('class', 'd3-tip')
            .offset([-10, 0])
            .html(function() {
                    return "<strong>Means:</strong> <span style='color:red'>" + [x_means, y_means] + "</span>";
            });

    svg.call(tip);

    circle.enter().append("circle")
            .attr('class', 'means')
            .attr("r", 10)
            .on("mouseover", tip.show)
            .on("mouseover", tip.hide);

    circle
            .transition().ease("linear").duration(200)
            .attr("cx", function(d, i) { return X(d[0]); })
            .attr("cy", function(d, i){return Y(d[1]);});


    circle.exit().remove();
}

有关如何使用[x_means, y_means]值在图表上显示工具提示的任何想法?

谢谢!

修改:我有this visualisation,我想在红色圆圈上显示工具提示。

function plotMeans(){
    var circle = svg.selectAll("circle.means")
            .data(numeric.transpose([x_means, y_means]));

    console.log(numeric.transpose([x_means, y_means])); //returns 3 pairs of X-Y values

    var tip = d3.tip()
            .attr('class', 'd3-tip')
            .offset([-10, 0])
            .html(function() {
                for(var i = 0; i < k; i++){
                    return "<strong>Means:</strong> <span style='color:red'>" + JSON.stringify(meansjson) + "</span>";
                }

            });

    svg.call(tip);

    circle.enter().append("circle")
            .attr('class', 'means')
            .attr("r", 10)
            .on("mouseover", tip.show)
            .on("mouseout", tip.hide);

    circle
            .transition().ease("linear").duration(200)
            .attr("cx", function(d, i) { return X(d[0]); })
            .attr("cy", function(d, i){return Y(d[1]);});


    circle.exit().remove();
}

我想用工具提示显示红色圆圈的X和Y值。 console.log(numeric.transpose([x_means, y_means]));会返回三对X-Y值,但我不知道如何在红点上正确显示这些值。

1 个答案:

答案 0 :(得分:1)

你所做的很酷。你犯了一个小错误:

当鼠标悬停在圆圈上时,您需要显示工具提示,当鼠标指针关闭时,您想隐藏它。因此,如果您更改以下行:

        .on("mouseover", tip.show)
        .on("mouseover", tip.hide);

为:

        .on("mouseover", tip.show)
        .on("mouseout", tip.hide);

它有效。

<强> __更新__

只需添加此功能

即可
function average(dataArray){
  var sum=0;
  for(var i=0; i< dataArray.length; i++){
    sum=sum+dataArray[i];
  }
  return sum/dataArray.length;
}

并按如下方式使用:

return "<strong>Means:</strong> <span style='color:red'>" + [average(x_means), average(y_means)] + "</span>";