Search code examples
javascriptsvgd3.jscircle-pack

Undefined function when loading D3 circle pack


I'm building a bubble chart from d3js but keep receiving a TypeError: undefined is not a function with the enter() method. I've tried just about everything and I can't determine why this error is being produced besides the fact that the filter method is returning null. Currently the bubble chart itself is not displayed.

    var diameter = 310,
      format = d3.format(",d"),
      color = d3.scale.category20c();

    var bubble = d3.layout.pack()
      .sort(null)
      .size([diameter, diameter])
      .padding(1.5);

    var svg = d3.select("bubble")
      .append("svg")
      .attr("width", diameter)
      .attr("height", diameter)
      .attr("class", "bubble");


    var node = svg.selectAll(".node")
      .data(bubble.nodes({children: [{packageName: "food", className: "food", value: 100}]}))
      .filter(function(d) { return !d.children; })
      // ================================
      // This is causing the error below
      // ================================
      .enter()
      .append("g")
      .attr("class", "node")
      .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });

    node.append("title")
      .text(function(d) { return d.className + ": " + format(d.value); });

    node.append("circle")
      .attr("r", function(d) { return d.r; })
      .style("fill", function(d) { return color(d.packageName); });

    node.append("text")
      .attr("dy", ".3em")
      .style("text-anchor", "middle")
      .text(function(d) { return d.className.substring(0, d.r / 3); });

    d3.select(self.frameElement).style("height", diameter + "px");

JsFiddle: http://jsfiddle.net/26Tra/


Solution

  • In your data binding, you are using keys such as packageName and className that are generated by the classes function, which is missing from your code. I added it and now your data binding is correct:

    var node = svg.selectAll(".node")
        .data(bubble.nodes(classes(root)).filter(function (d) {return !d.children;}))
      .enter()
        ...
    

    NOTE: because I mocked some very simple data, with only one packageName, fruits, I used className instead of packageName for the coloring. I also changed the color category to category10() to give it more contrast.

    Complete FIDDLE.