如何将交互式功能(线和标签)添加到D3折线图?

时间:2014-02-13 10:16:32

标签: javascript d3.js

我是D3.js的新手,目前正为我的一个项目开发line chart。我参考了文档和示例here并创建了我自己的版本here。 现在,我打算在这里添加两个互动功能:

  1. 在图表中鼠标悬停时,绘制一条到最近数据点的垂直线。
  2. 在此垂直线旁边显示带有X和Y属性的标签。
  3. 要使此功能更加清晰,请参阅此example

    以下是我尝试过的建议:

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

    然而,线条矩形不显示。我一直在谷歌搜索,但没有白费。我错过了什么?

    jsFiddle

1 个答案:

答案 0 :(得分: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