繁体   English   中英

如何使用d3.js在饼图附近显示工具提示?

[英]How to get a tooltip show up near the pie slice using d3.js?

小提琴的例子

如何获得工具提示以更靠近悬停的切片显示? 我无法使d3.pageXOffsetd3.pageYOffset (如本示例 )正常工作。 如何获得工具提示悬停的饼图切片位置?

无法运作:

path.on('mouseover', function(d) { 
    tooltip.style("top", d3.pageYOffset + "px").style("left", d3.pageXOffset + "px")
});

完整代码:

    var dataset = 
        [
            {item:"Boy",result:12},
            {item:"Girl",result:24},
            {item:"Woman",result:60},
            {item:"Man",result:10}                     
        ]
    var width = 280;
    var height = 280;
    var radius = Math.min(width, height) / 2;
    var color = d3.scale.category10();

    var svg = d3.select('#area')
      .append('svg')
      .attr('width', width)
      .attr('height', height)
      .append('g')
      .attr('transform', 'translate(' + (width / 2) + 
        ',' + (height / 2) + ')');
    var arc = d3.svg.arc()
      .outerRadius(radius);
    var pie = d3.layout.pie()
      .value(function(d) { return d.result; })
      .sort(null);
    var path = svg.selectAll('path')
      .data(pie(dataset))
      .enter()
      .append('path')
      .attr('d', arc)
      .attr('fill', function(d, i) { 
        return color(d.data.item);
      });
    var tooltip = d3.select('#area').append('div').attr('class', 'tooltip');                           
    path.on('mouseover', function(d) { 
               var matrix = this.getScreenCTM()
        .translate(+this.getAttribute("cx"),
                 +this.getAttribute("cy"));

        var total = d3.sum(dataset.map(function(d) {               
          return d.result;                                           
        }));     
        var percent = Math.round(1000 * d.data.result / total) / 10; 
        tooltip.style("top", d3.pageYOffset + "px")
        .style("left",d3.pageXOffset + "px")
        .style('display', 'block') 
        .style("opacity", 1)
        .append('div')                                         
        .attr('class', 'label')                                   
        .append('div')                                        
        .attr('class', 'count')                                      
        .append('div')                                           
        .attr('class', 'percent'); 

        tooltip.select('.label').html(d.data.item);               
        tooltip.select('.count').html(d.data.result);               
        tooltip.select('.percent').html(percent + '%'); 

      });                                                           

      path.on('mouseout', function() {                             
        tooltip.style('display', 'none');                          
      });                       

使用d3.event

tooltip.style("top", d3.event.y + "px").style("left", d3.event.x + "px");

我也将其放入mousemove处理程序中以获得更好的结果。

更新小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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