2015-04-19 32 views
0

出于某种原因,selectAll(“g”).data(data).enter()。append(“g”)不起作用?

chart.selectAll("g").data(data).enter().append("g") 

不起作用,但

chart.selectAll("rect").data(data).enter().append("rect") 

确实工作。通过“工作”,我的意思是chart代表的元素最后包含许多“rect”/“g”,每个数据项一个,第二行导致元素最终包含许多rect,但如果使用g则不会出现任何内容。想法,为什么从rectg一个简单的变化会导致错误

代码:

var chart = svg.append("g") 
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); 

    // setup chart axis. 
     chart.append("g") 
       .attr("class", "x axis") 
       .call(xAxis); 

      chart.append("g") 
       .attr("class", "y axis") 
       .call(yAxis) 
      .append("text") 
       .attr("transform", "rotate(-90)") 
       .attr("y", 6) 
       .attr("dy", ".71em") 
       .style("text-anchor", "end") 
       .text(yLabel); 

    // Pertinent code here  
    var rows = chart.selectAll("g").data(data).enter().append("g"); 

回答

1

不知道你想要什么,但:

如果你想要的东西,如:

svn 
    g //one g for every data row 
    g //y axis 
    g //x axis 

那么这样的事情应该工作:

var chart = svg 
var chartLines = chart 
.append("g") 
.attr("transform", "translate(" + margin.left + "," + margin.top + ")") 
.attr("class", "line"); 

// setup chart axis. 
    chart.append("g") 
      .attr("class", "x axis") 
      .call(xAxis); 

     chart.append("g") 
      .attr("class", "y axis") 
      .call(yAxis) 
     .append("text") 
      .attr("transform", "rotate(-90)") 
      .attr("y", 6) 
      .attr("dy", ".71em") 
      .style("text-anchor", "end") 
      .text(yLabel); 

// Pertinent code here  
var rows = chart.selectAll(".line").data(data).enter().append("g"); 
0

这是因为已经在运行这段代码有很多网页上g元素 - 他们中的一些你所添加的,一些当您调用轴组件时,它们由D3添加。然而,没有rect元素,所以代码工作。

周围有此几种方式 - 你可以运行数据首先结合到g元素的代码,添加轴和图表中单独g元素,一类添加到g元素,你绑定数据到,或这些的任何组合。

更多的背景和this tutorial的例子。

相关问题