【问题标题】:How to add interactive features (line and label) to a D3 line chart?如何向 D3 折线图添加交互功能(折线和标签)?
【发布时间】:2014-03-12 03:42:48
【问题描述】:

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

  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

【问题讨论】:

标签: javascript d3.js


【解决方案1】:
//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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    • 2018-02-14
    相关资源
    最近更新 更多