2014-02-13 58 views
0

我是D3.js的新手,目前正在爲我的一個項目開發line chart。我參考了文檔和示例here並創建了我自己的版本here。 現在,我打算加入這裏有兩個互動功能:如何將交互式功能(線條和標籤)添加到D3折線圖?

  1. 鼠標懸停在圖表中畫一條垂直線到最近的數據點。
  2. 在垂直線旁邊顯示X和Y屬性的標籤。

若要使此功能更清晰,請參閱此example

這裏是我試圖從一個建議傳來:

svg.append("g")  // creating new 'group' element 
.selectAll('rect')  // adding a rectangle for the label 
.selectAll('line'); // adding a line 

然而,線答矩形犯規出現。我一直在谷歌搜索很多,但沒有白費。我錯過了什麼?

jsFiddle

+0

你見過[NVD3](http://nvd3.org/)嗎? –

+0

@LarsKotthoff:謝謝你的建議,但我只限於使用D3庫。使用.selectAll('rect')和.selectAll('line')的 –

+1

,您將選擇剛剛創建的'g'元素中的所有矩形和線條,這是空的。這就是爲什麼你沒有得到這些元素出現。 – tomtomtom

回答

2
//create groups for line and label (and invisible selection area) 
var infos = svg.append('g') 
    .selectAll('rect') 
    .data(data) 
    .enter() 
    .append('g') 
//move to datapoint location 
    .attr('transform',function(d,i){d.x = x(d.date) ; d.y = 0; return "translate(" + d.x + "," + d.y + ")";}); 

//create and select line "rectangles" (easier than doing actual lines) 
infos.append("rect") 
.attr('class','line') 
.attr('height', height) 
.attr('width', 1) 
.attr('opacity',0); 

//create and select line "rectangles" (easier than doing actual lines) 
infos.append("rect") 
.attr('class','area') 
.attr('height', height) 
//should probably do something to make sure they don't overlap, such as measure distance between neighbours and use that as width 
.attr('width', width/data.length/2) 
.attr('opacity',0) 
//move so that the data point is in the middle 
.attr('x',-width/data.length/4) 
.on('mouseover', function(){ 
    g_elem = this.parentNode; 
    d3.select(g_elem).selectAll(".line").attr("opacity",1); 
}) 
.on('mouseout', function(){ 
    g_elem = this.parentNode; 
    d3.select(g_elem).selectAll(".line").attr("opacity",0); 
}); 

http://jsfiddle.net/SKb8W/7/

對於標籤,這裏是一個有用的例子:http://jsfiddle.net/WLYUY/5/(從D3.js: Position tooltips using element position, not mouse position?

而對於使用鼠標座標,你可以這樣做:

var coordinates = [0, 0]; 
coordinates = d3.mouse(this); 
var x = coordinates[0]; 
var y = coordinates[1]; 

(來自Mouse position in D3