工具提示不适用于带有d3.js的条形图

时间:2014-12-10 09:36:29

标签: angularjs d3.js

我正在使用与angularJs集成的d3.js。但它在调用tip.show和tip.hide时无法正常工作并出错。

var chart = d3.select(element[0])
     .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 + ")"); 

chart.call(tip);

chart.selectAll(".bar")
    .data(data)
    .enter().append("rect")
    .attr("class", function(d) { return d.value < 0 ? "bar negative" : "bar positive"; })    
    .attr("x", function(d) { return x(d.name); })
    .attr("y", height)
    .attr("height", 0)
    .transition().duration(2000)
    .attr("y", function(d) {return y(Math.max(0, d.value)); })
    .attr("height", function(d) {return Math.abs(y(d.value) - y(0)); })    
    .attr("width", x.rangeBand())
    .on('mouseover', tip.show)
    .on('mouseout', tip.hide); 

完整的工作示例在小提琴中给出

http://jsfiddle.net/HB7LU/8984/

2 个答案:

答案 0 :(得分:2)

您在每次转换时绑定鼠标侦听器。将听众绑定到选择

 chart.selectAll(".bar")
      .data(data)
      .enter().append("rect")
      .attr("class", function(d) { return d.value < 0 ? "bar negative" : "bar positive"; })    
      .attr("x", function(d) { return x(d.name); })
      .attr("y", height)
      .attr("height", 0)
      .on('mouseover', tipX.show) //Moved up
      .on('mouseout', tipX.hide)  //Moved up
      .transition().duration(2000)
      .attr("y", function(d) {return y(Math.max(0, d.value)); })
      .attr("height", function(d) {return Math.abs(y(d.value) - y(0)); })    
      .attr("width", x.rangeBand());

同时更新此代码,因为d是此处的对象。

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

以下是更新后的fiddle

答案 1 :(得分:0)

我认为你可以画一个div来做这个伎俩。 我不确定这是不是一个好方法。

var div = d3.select('body').append('div')   
.attr('class', 'tooltip')               
.style('opacity', 0);

fiddle