2013-01-19 47 views
1

试图仿效该图:http://www.nytimes.com/interactive/2012/11/30/us/tax-burden.html同时光标

这里是赤裸演绎:http://jsfiddle.net/jd5Ym/6/

我不能让不同的光标每次随访数据为自己的城市。我一次只能做一个。我的代码依赖于这个功能:

function mousemove() { 
    // p is the fraction of a graph traversed. decimalize strips integers. 
var p=decimilize((x0.rangeBand()-d3.mouse(this)[0]+margin.left)/(x0.rangeBand())); 
var u=data[Math.round(data.length-p*data.length)]; 
var v=cities[1].values[Math.round(data.length-p*data.length)]; 
cursor.data(data).attr("transform", "translate(" + (x1(u.date)) +","+y(v.temperature)+")"); 
     } 

它说:“V =城市[1]”,该指数决定城市的数据要跟踪的。我希望它能为每个城市本身编制索引。但是,当我尝试使用“功能(d,我){...}”设置,它不会奏效。我尝试在City的声明中的转换属性中追加mousemove函数,但这也不起作用。

我是一个开始的程序员,所以也许这很容易。数据结构和解析来自mike bostock的例子。

回答

1

您应该使用selectAll('。cities')。each(...)来遍历所有城市并独立更新其游标。

function mousemove() { 
    // the proportion of the way across any given graph that the mouse is 
    var mouseX = d3.mouse(this)[0] 
    var graph_width = x0.rangeBand() 
    // the corresponding data 
    var index = Math.floor((mouseX/graph_width) * data.length); 
    d3.selectAll('.city') 
    .each(function(d, i){ 
     var u = cities[i].values[index]; 
     d3.select(this).select('.cursor') 
     .attr('transform', 'translate(' + x1(u.date) + ',' + y(u.temperature) + ')') 
    }) 
} 

在这里看到完整的工作示例:http://jsfiddle.net/jd5Ym/9/