条形图d3.js顶部的圆圈

时间:2016-06-13 12:50:40

标签: javascript d3.js

我根据Mike Bostock的教程制作分组条形图。

我无法弄清楚如何在我的条形图上放置圆圈作为悬停时的工具提示,就像在this tutorial中一样,除了它在条形图上而不是在一条线上。< / p>

我尝试添加这样的圈子:

svg.selectAll("dot")    
    .data(data)         
.enter().append("circle")                               
    .attr("r", 5)       
    .attr("cx", function(d) { return x1(d.name); })      
    .attr("cy", function(d) { return y(d.value); })         
    });

但我得到NaN值。我很困惑我应该使用哪个变量来获得正确的cx和cy。

这是我的code

有什么想法吗?

谢谢

1 个答案:

答案 0 :(得分:1)

您将获得NaN值,因为您的数据连接不正确,您正在尝试获取数据中当前不存在的值。为了获得这些值,您需要引用data.years。

这是我的方法:

// Inheriting data from parent node and setting it up, 
// add year to each object so we can make use for our 
// mouse interactions.
year.selectAll('.gender-circles') 
  .data(function(data) {
    return data.years.map(function(d) {
      d.year = data.year;
      return d;
    })
  })
  .enter().append('circle')
  .attr("class", function(d) {
    return "gender-circles gender-circles-" + d.year;
  })
  .attr("r", 10)
  .attr('cx', function(d) {
    console.log(d)
    return x1(d.name) + 6.5;
  })
  .attr('cy', function(d) {
    return y(d.value) - 15;
  })
  .style('display', 'none'); // default display

// ....

// Using an invisible rect for mouseover interactions
year.selectAll('.gender-rect-interaction') 
  .data(function(d) { // Inheriting data from parent node and setting it up
    return [d];
  })
  .enter().append('rect')
  .attr("width", x0.rangeBand()) // full width of x0 rangeband
  .attr("x", function(d) { 
    return 0;
  })
  .attr("y", function(d) {
    return 0;
  })
  .attr("height", function(d) { // full height
    return height;
  })
  .style('opacity', 0) // invisible!
  .on('mousemove', function(d) { // show all our circles by class
    d3.selectAll('.gender-circles-' + d.year)
      .style('display', 'block');
  })
  .on('mouseout', function(d) { // hide all our circles by class
    d3.selectAll('.gender-circles-' + d.year)
      .style('display', 'none');
  });

工作plnkr:https://plnkr.co/edit/oH4KXdxdIW82nLGv46NI?p=preview