2016-02-28 33 views
0

更新:所以,我能够正确地获取数据到我的cx/cy数据(吐出正确的值),但元素给了我一个错误的NaN。在点线图d3上绘制点(在流星中做这件事)

所以我得到的只具半径3个元素。

原帖:

我有一个关于在D3线图上呈现点的问题。我会尽力给出相关代码的每一部分(以及稍微复杂一些的数据结构)。

所以,目前,1个黑点呈现在我的图表的左上角,但在其他地方。它看起来像我得到3常量当我console.log cx和cy返回函数。我究竟做错了什么?

城市是目前,返回3个对象的阵列。

每个对象具有以下结构:

Object { 
name: 'string', 
values: array[objects] 
} 

值阵列如下:

objects { 
Index: number, 
Time: date in a particular format 
} 

好。相关代码时间:

 var points = svg.selectAll('dot') 
     .data(cities); 



     console.log('Points is :', points) 


     points 
     .enter().append('circle') 
     // .data(function(d) {console.log("data d is :", d); return d}) 
     .data(cities) 
     .attr('cx', function(d) { 
      return x(new Date(d.values.forEach(function(c) { 
      console.log("cx is: ", c.Time); 
      return c.Time; 
      })))}) 
     .attr('cy', function(d) { 
      return y(d.values.forEach(function(c) { 
      console.log("cy is: ", c.Index) 
      return c.Index; 
      })) 
     }) 
     .attr('r', dotRadius()); 



     points.exit().remove(); 

     // points.attr('class', function(d,i) { return 'point point-' + i }); 

     d3.transition(points) 
     .attr('cx', function(d) { 
      return x(new Date(d.values.forEach(function(c) { 
      console.log("cx is: ", c.Time); 
      return c.Time; 
      })))}) 
     .attr('cy', function(d) { 
      return y(d.values.forEach(function(c) { 
      console.log("cy is: ", c.Index) 
      return c.Index; 
      })) 
     }) 
     .attr('r', dotRadius()) 

回答

1

这里您需要嵌套的选择。

此:

.attr('cx', function(d) { 
    return x(new Date(d.values.forEach(function(c) { 
    console.log("cx is: ", c.Time); 
    return c.Time; 
})))}) 

是完全无效的。其中一个,attr期望设置一个值,您试图让它处理一组值。二,forEach设计只返回未定义。只是不去工作。

你应该做这样的事情:

var g = svg.selectAll(".groupOfPoint") //<-- top level selection 
     .data(cities) 
    .enter().append("g") 
     .attr("class", "groupOfPoint"); 

    g.selectAll(".point") //<-- this is the nested selection 
    .data(function(d){ 
     return d.values; //<-- we are doing a circle for each value 
    }) 
    .enter().append("circle") 
    .attr("class", "point") 
    .attr('cx', function(d){ 
     return x(d.Time); 
    }) 
    .attr('cy', function(d){ 
     return y(d.Index); 
    }) 
    .attr('r', 5) 
    .style('fill', function(d,i,j){ 
     return color(j); 
    }); 

既然你似乎是建立关闭此example的,我已经modified it here是一个散点图,而不是线。

+0

感谢,这正是问题。我的数据太高了。 当我有更复杂的数据结构的工作,我会牢记这一点。我确实使用该示例来解决我遇到的问题(IE,我想根据列分隔我的数据行),但是我的数据结构非常非常不同:) – Tulun