2013-10-25 17 views
1

我在D3中製作了散點圖,圓圈表示每個數據點。這裏是我的代碼:在鼠標懸停時創建連接圓的線

viz.selectAll('circle') 
    .data(data) 
    .enter() 
    .append('circle') 
    .attr("cx", function(d) {return x(d.x)}) 
    .attr("cy", function(d) {return y(d.y)}) 
    .attr("r", 5) 
    .attr("fill", function(d) {return d.color}) 
    .on('mouseover', function(d){ 
     console.log(d.color) 
    }) 

我想要做的是,當給定圓上徘徊,通過具有相同顏色的線連接各界。我怎樣才能做到這一點?我可以將顏色記錄到控制檯中,但我不明白如何通過鼠標單擊時通過一條線將所有點連接到相同的顏色?

回答

1

您可以將顏色代碼分配給您的圈子。使用d3.selectAll在鼠標懸停上檢索它們。然後檢索它們的座標並傳遞座標以繪製d3.svg.line。

svg.selectAll(".dot") 
    .data(data) 
    .enter().append("circle") 
    .attr("class", function(d) { 
     return 'dot color-' + color(d.species).replace('#',''); 
     }) 
    .attr("r", 3.5) 
    .attr("cx", function(d) { return x(d.sepalWidth); }) 
    .attr("cy", function(d) { return y(d.sepalLength); }) 
    .attr("dot-color", function(d) { return color(d.species).replace('#',''); }) 
    .style("fill", function(d) { return color(d.species); }) 
    .on("mouseover", function() { 
     d3.selectAll(".color-" + $(this).attr("dot-color")) 
      .attr("r", 5.5); 
    }) 
    .on("mouseout", function() { 
     d3.selectAll(".color-" + $(this).attr("dot-color")) 
      .attr("r", 3.5); 
    }); 

這裏的色彩懸停一個例子:

http://vida.io/documents/KinEKRkSPSfStA4Eu

1

您也可以不依賴於一個共同的類屬性做到這一點。在鼠標懸停處理程序中:

d3.selectAll('.dot') 
    .filter(function (dOther) { return d.color == dOther.color }) 
    .attr('r', 3.5)