2016-06-13 2 views
2

Я делаю сгруппированную гистограмму на основе учебника Майка Бостока.Круги на верхней части гистограммы d3.js

Я не могу понять, как накладывать круги поверх моих баров, чтобы действовать как подсказка при наведении курсора, как в this tutorial, за исключением того, что он находится на барах, а не на линии.

Я попытался добавлением кругов, как это:

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.

Любые идеи?

Спасибо

ответ

0

вы получите значение 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

+0

Это идеальный вариант! Я настроил его немного, чтобы соответствовать моим потребностям, но вы очень помогли, спасибо! – macdows