LazerSharks
LazerSharks

Reputation: 3155

selectAll("g").data(data).enter().append("g") does not work?

For some reason,

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

does not work, but

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

does work. By "work", I mean the element represented by chart finally contains many "rect"/"g, one for each data item. The second line causes the element to finally contain many rect, but nothing will appear if g is used. Any ideas why a simple change from rect to g will cause a bug?

Code:

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");

Upvotes: 0

Views: 878

Answers (2)

Lars Kotthoff
Lars Kotthoff

Reputation: 109252

This is because there are a lot of g elements on the page already when you run this code -- some of them added by you, some of them added by D3 when you call the axis component. There are however no rect elements, so that code works.

There are several ways around this -- you can either run the code that binds the data to the g elements first, add axis and chart in separate g elements, add a class to the g elements that you're binding the data to, or any combination of these.

Some more background and examples in this tutorial.

Upvotes: 0

Jurgo Boemo
Jurgo Boemo

Reputation: 1768

not sure what you want, but:

if you want something like:

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

then something like this should work:

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");

Upvotes: 1

Related Questions