Javascript D3树映射-递归框未出现

Javascript D3树映射-递归框未出现,javascript,json,d3.js,Javascript,Json,D3.js,为了更好地理解D3的工作原理,我尝试复制以下D3可缩放树形图: TL;DR:我只看到JSON对象的前两个子对象,而不是孙子辈等等。当我单击其中一个子节点时,我的浏览器中将打开一个空的HTML文档(而不是“”,这是在原始俄亥俄州树状图中单击叶节点时得到的) 我的调试尝试: 在我的控制台中,作为测试,我将来自“zoomabletreemap.JSON”的JSON值存储为一个名为“treemap”的变量,并且我可以访问诸如“treemap.children[0].children”之类的属性。但当我

为了更好地理解D3的工作原理,我尝试复制以下D3可缩放树形图:

TL;DR:我只看到JSON对象的前两个子对象,而不是孙子辈等等。当我单击其中一个子节点时,我的浏览器中将打开一个空的HTML文档(而不是“”,这是在原始俄亥俄州树状图中单击叶节点时得到的)

我的调试尝试: 在我的控制台中,作为测试,我将来自“zoomabletreemap.JSON”的JSON值存储为一个名为“treemap”的变量,并且我可以访问诸如“treemap.children[0].children”之类的属性。但当我试图通过在脚本中添加console.log语句来输出这些子级时,我得到了“undefined”。例如,在我的脚本代码中,标记为:

/* write children rectangles */
我添加了以下console.log语句:

g.selectAll(".child")
  .data(function(d) {
    console.log(d);
    console.log(d.children);
    return d.children || [d];
  })
输出如下:

Object {name: "International Relations", value: 42257, depth: 1, parent: Object, area: 0.6293113718949187…}
area: 0.6293113718949187
depth: 1
dx: 620
dy: 302.06945850956095
name: "International Relations"
parent: Object
value: 42257
x: 0
y: 0
z: true
__proto__: Object

undefined 

Object {name: "Political Methodology", value: 24891, depth: 1, parent: Object, area: 0.37068862810508135…}
area: 0.37068862810508135
depth: 1
dx: 620
dy: 177.93054149043905
name: "Political Methodology"
parent: Object
value: 24891
x: 0
y: 302.06945850956095
z: false
__proto__: Object

undefined 
显然,前两个子节点(“国际关系”和“政治方法”)正在以某种方式被覆盖,这将删除所有子节点的“children”属性。我已经将我的代码与原始源代码进行了比较,以检查代码的差异,我没有看到任何明显的差异。谁能告诉我我做错了什么

这里有一把JS小提琴,我希望它能起作用,但不能:

下面是我的HTML和JS脚本:

<!DOCTYPE html>
<meta charset="utf-8">
<title>Zoomable Treemap</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="../d3.v3/d3.v3.js"></script>

<link rel="stylesheet" href="example.css">

<p id="chart">
 <script>
  var margin = {top: 20, right: 0, bottom: 0, left: 0},
  width = 620,
  height = 500 - margin.top - margin.bottom,
  formatNumber = d3.format(",d"),
  transitioning;

  /* create x and y scales */
  var x = d3.scale.linear()
  .domain([0, width])
  .range([0, width]);

  var y = d3.scale.linear()
  .domain([0, height])
  .range([0, height]);

  var treemap = d3.layout.treemap()
  .children(function(d, depth) {
    return depth ? null : d.children;
  })
  .sort(function(a, b) { return a.value - b.value; })
  .ratio(height / width * 0.5 * (1 + Math.sqrt(5)))
  .round(false);

/* create svg */
  var svg = d3.select("#chart").append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.bottom + margin.top)
  .style("margin-left", -margin.left + "px")
  .style("margin.right", -margin.right + "px")
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
  .style("shape-rendering", "crispEdges");

  var grandparent = svg.append("g")
  .attr("class", "grandparent");

  grandparent.append("rect")
  .attr("y", -margin.top)
  .attr("width", width)
  .attr("height", margin.top);

  grandparent.append("text")
  .attr("x", 6)
  .attr("y", 6 - margin.top)
  .attr("dy", ".75em");

  /* load in data, display root */
d3.json("zoomabletreemap.json", function(root) {


  initialize(root);
  accumulate(root);
  layout(root);
  display(root);

  function initialize(root) {
    root.x = root.y = 0;
    root.dx = width;
    root.dy = height;
    root.depth = 0;
  }

  // Aggregate the values for internal nodes. This is normally done by the
  // treemap layout, but not here because of our custom implementation.
  function accumulate(d) {
    return d.children
    ? d.value = d.children.reduce(function(p, v) { return p + accumulate(v); }, 0)
    : d.value;
  }

  // Compute the treemap layout recursively such that each group of siblings
  // uses the same size (1×1) rather than the dimensions of the parent cell.
  // This optimizes the layout for the current zoom state. Note that a wrapper
  // object is created for the parent node for each group of siblings so that
  // the parent’s dimensions are not discarded as we recurse. Since each group
  // of sibling was laid out in 1×1, we must rescale to fit using absolute
  // coordinates. This lets us use a viewport to zoom.
  function layout(d) {
    if (d.children) {
      treemap.nodes({children: d.children});
      d.children.forEach(function(c) {
        c.x = d.x + c.x * d.dx;
        c.y = d.y + c.y * d.dy;
        c.dx *= d.dx;
        c.dy *= d.dy;
        c.parent = d;
        layout(c);
      });
    }
  }

  /* display show the treemap and writes the embedded transition function */
  function display(d) {
    /* create grandparent bar at top */
    grandparent
      .datum(d.parent)
      .on("click", transition)
      .select("text")
      .text(name(d));

    var g1 = svg.insert("g", ".grandparent")
      .datum(d)
      .attr("class", "depth");
    /* add in data */
    var g = g1.selectAll("g")
      .data(d.children)
      .enter().append("g");

    /* transition on child click */
    g.filter(function(d) { return d.children; })
      .classed("children", true)
      .on("click", transition);

    /* write children rectangles */
    g.selectAll(".child")
      .data(function(d) {
        return d.children || [d];
      })
      .enter().append("rect")
      .attr("class", "child")
      .call(rect);

    /* write parent rectangle */
    g.append("rect")
      .attr("class", "parent")
      .call(rect)
      /* open new window based on the json's URL value for leaf nodes */
      /* Chrome displays this on top */
      .on("click", function(d) {
        if(!d.children){
          window.open(d.url);
        }
      })
      .append("title")
      .text(function(d) { return formatNumber(d.value); });

    /* Adding a foreign object instead of a text object, allows for text wrapping */
    g.append("foreignObject")
      .call(rect)
      /* open new window based on the json's URL value for leaf nodes */
      /* Firefox displays this on top */
      .on("click", function(d) {
        if(!d.children){
          window.open(d.url);
        }
      })
      .attr("class","foreignobj")
      .append("xhtml:div")
      .attr("dy", ".75em")
      .html(function(d) { return d.name; })
      .attr("class","textdiv"); //textdiv class allows us to style the text easily with CSS
      /* create transition function for transitions */

    function transition(d) {
      if (transitioning || !d) return;
      transitioning = true;

      var g2 = display(d),
        t1 = g1.transition().duration(750),
        t2 = g2.transition().duration(750);

      // Update the domain only after entering new elements.
      x.domain([d.x, d.x + d.dx]);
      y.domain([d.y, d.y + d.dy]);

      // Enable anti-aliasing during the transition.
      svg.style("shape-rendering", null);

      // Draw child nodes on top of parent nodes.
      svg.selectAll(".depth").sort(function(a, b) { return a.depth - b.depth; });

      // Fade-in entering text.
      g2.selectAll("text").style("fill-opacity", 0);
      g2.selectAll("foreignObject div").style("display", "none"); /*added*/

      // Transition to the new view.
      t1.selectAll("text").call(text).style("fill-opacity", 0);
      t2.selectAll("text").call(text).style("fill-opacity", 1);
      t1.selectAll("rect").call(rect);
      t2.selectAll("rect").call(rect);

      t1.selectAll(".textdiv").style("display", "none"); /* added */
      t1.selectAll(".foreignobj").call(foreign); /* added */
      t2.selectAll(".textdiv").style("display", "block"); /* added */
      t2.selectAll(".foreignobj").call(foreign); /* added */

      // Remove the old node when the transition is finished.
      t1.remove().each("end", function() {
        svg.style("shape-rendering", "crispEdges");
        transitioning = false;
      });

    }//endfunc transition

    return g;
  }//endfunc display

  function text(text) {
    text.attr("x", function(d) { return x(d.x) + 6; })
    .attr("y", function(d) { return y(d.y) + 6; });
  }

  function rect(rect) {
    rect.attr("x", function(d) { return x(d.x); })
    .attr("y", function(d) { return y(d.y); })
    .attr("width", function(d) { return x(d.x + d.dx) - x(d.x); })
    .attr("height", function(d) { return y(d.y + d.dy) - y(d.y); });
  }    

  function foreign(foreign){ /* added */
    foreign.attr("x", function(d) { return x(d.x); })
    .attr("y", function(d) { return y(d.y); })
    .attr("width", function(d) { return x(d.x + d.dx) - x(d.x); })
    .attr("height", function(d) { return y(d.y + d.dy) - y(d.y); });
  }

  function name(d) {
    return d.parent ? name(d.parent) + "." + d.name : d.name;
  }
});


</script>

可缩放树形图

var margin={top:20,right:0,bottom:0,left:0}, 宽度=620, 高度=500-页边距.顶部-页边距.底部, formatNumber=d3.格式(“,d”), 过渡; /*创建x和y比例*/ var x=d3.scale.linear() .domain([0,宽度]) .范围([0,宽度]); 变量y=d3.scale.linear() .domain([0,高度]) .范围([0,高度]); var treemap=d3.layout.treemap() .儿童(功能(d,深度){ 返回深度?空:d.子项; }) .sort(函数(a,b){返回a.value-b.value;}) .比率(高度/宽度*0.5*(1+数学sqrt(5))) .圆形(假); /*创建svg*/ var svg=d3.选择(“图表”).追加(“svg”) .attr(“宽度”,宽度+边距。左侧+边距。右侧) .attr(“高度”,高度+边距。底部+边距。顶部) .style(“左边距”、-margin.left+“px”) .style(“margin.right”、-margin.right+“px”) .附加(“g”) .attr(“转换”、“平移”(“+margin.left+”,“+margin.top+”) .风格(“形状渲染”、“边缘”); var祖父母=svg.append(“g”) .attr(“阶级”、“祖父母”); 祖父母。附加(“rect”) .attr(“y”,-margin.top) .attr(“宽度”,宽度) .attr(“高度”,边距,顶部); 祖父母。附加(“文本”) .attr(“x”,6) .attr(“y”,6-页边距。顶部) .attr(“dy”,“.75em”); /*加载数据,显示根目录*/ d3.json(“zoomabletreemap.json”),函数(根){ 初始化(根); 积累(根); 布局(根); 显示(根); 函数初始化(根){ root.x=root.y=0; root.dx=宽度; root.dy=高度; 根深度=0; } //聚合内部节点的值。这通常由 //树映射布局,但由于我们的自定义实现,这里没有。 函数累加(d){ 返回d.儿童 d.value=d.children.reduce(函数(p,v){返回p+accumulate(v);},0) :d.价值; } //递归计算树映射布局,使每组同级 //使用相同的大小(1×1),而不是父单元格的尺寸。 //这将优化当前缩放状态的布局 //为父节点为每组同级创建对象,以便 //当我们递归时,父维度不会被丢弃 //兄弟姐妹的比例为1×1,我们必须使用绝对值重新缩放以适应 //坐标。这让我们可以使用视口进行缩放。 功能布局(d){ 如果(d.儿童){ 树映射节点({children:d.children}); d、 儿童。forEach(函数(c){ c、 x=d.x+c.x*d.dx; c、 y=d.y+c.y*d.dy; c、 dx*=d.dx; c、 dy*=d.dy; c、 父代=d; 布局图(c); }); } } /*显示树映射并写入嵌入的转换函数*/ 功能显示(d){ /*在顶部创建祖父母酒吧*/ 祖父母 .基准面(d.母面) 。打开(“单击”,转换) .选择(“文本”) .文本(名称(d)); var g1=svg.insert(“g”,“祖父母”) .基准(d) .attr(“类别”、“深度”); /*附加数据*/ 变量g=g1。选择全部(“g”) .数据(d.儿童) .enter().append(“g”); /*子单击时的转换*/ g、 筛选器(函数(d){返回d.children;}) .分类(“儿童”,真实) 。打开(“点击”,转换); /*将子对象写入矩形*/ g、 全选(“.child”) .数据(功能(d){ 返回d.children | |[d]; }) .enter().append(“rect”) .attr(“类”、“子类”) .呼叫(rect); /*写入父矩形*/ g、 附加(“rect”) .attr(“类”、“父类”) .call(rect) /*根据叶节点的json URL值打开新窗口*/ /*Chrome在顶部显示这个*/ .打开(“单击”,功能(d){ 如果(!d.children){ 打开(d.url); } }) .附加(“标题”) .text(函数(d){返回formatNumber(d.value);}); /*添加外来对象而不是文本对象,允许文本换行*/ g、 附加(“外来对象”) .call(rect) /*根据叶节点的json URL值打开新窗口*/ /*Firefox会在顶部显示这一点*/ .打开(“单击”,功能(d){ 如果(!d.children){ 打开(d.url); } }) .attr(“类别”、“外国对象”) .append(“xhtml:div”) .attr(“dy”,“.75em”) .html(函数(d){返回d.name;}) .attr(“class”,“textdiv”);//textdiv类允许我们使用CSS轻松设置文本样式 /*为转换创建转换函数*/ 功能转换(d){

{
 "name": "Sitemap",
 "children": [
  {
   "name": "International Relations",
   "children": [
    {
     "name": "Systemic Theory",
     "children": [
      {"name": "Great Powers", "value": 3938, "url": "http://polisci.osu.edu"},
      {"name": "Systemic Politics", "value": 743, "url": "http://polisci.osu.edu"}
     ]
    },
    {
     "name": "International Conflict",
     "children": [
      {"name": "Systemic Politics", "value": 3416, "url": "http://google.com"},
      {"name": "Causal Complexity", "value": 3416, "url": "http://bing.com"},
      {"name": "Deadly Doves", "value": 3416, "url": "http://polisci.osu.edu"},
      {"name": "Politcal Irrelevance", "value": 3416, "url": "http://polisci.osu.edu"},
      {"name": "The Fog of Peace: Uncertainty, War, and the Resumption of International Crises, <i>manuscript</i>", "value": 3416, "url": "http://polisci.osu.edu"},
      {"name": "Greed or Opportunity? Refining our Understanding of the Origins of Civil Wars, <i>manuscript</i>", "value": 3416, "url": "http://polisci.osu.edu"}
     ]
    },
    {
     "name": "Foreign Policy",
     "children": [
      {"name": "The Myth of American Isolationism", "value": 3416, "url": "http://polisci.osu.edu"}
     ]
    },
    {
     "name": "Courses",
     "children": [
      {"name": "IS 201", "value": 3416, "url": "http://polisci.osu.edu"},
      {"name": "PS 544", "value": 3416, "url": "http://polisci.osu.edu"},
      {"name": "PS 848", "value": 3416, "url": "http://polisci.osu.edu"}
     ]
    },
    {
     "name": "Dataverse",
     "children": [
      {"name": "Dataverse", "value": 3416, "url": "http://polisci.osu.edu"}
     ]
    }
   ]
  },
  {
   "name": "Political Methodology",
   "children": [
    {
     "name": "Theory and Methdology",
     "children": [
      {"name": "Interactions and Causal Complexity", "value": 3938, "url": "http://polisci.osu.edu"},
      {"name": "Theory and Methodology", "value": 743, "url": "http://polisci.osu.edu"},
      {"name": "Software", "value": 743, "url": "http://polisci.osu.edu"},
      {"name": "Courses", "value": 743, "url": "http://polisci.osu.edu"}
     ]
    },
    {
     "name": "Insteractions and Causal Cmplexity",
     "children": [
      {"name": "Hypothesis Testing and Multiplicative Interation Terms", "value": 3938, "url": "http://polisci.osu.edu"},
      {
        "name": "Causal Complexity",
        "children": [
         {"name": "Causal Complexity and the Study of Politics", "value": 3938, "url": "http://polisci.osu.edu"},
         {"name": "Political Irrelevance", "value": 743, "url": "http://polisci.osu.edu"},
         {"name": "boolean3 package for R", "value": 743, "url": "http://polisci.osu.edu"}
        ]
      }
     ]
    },
    {
     "name": "Software",
     "children": [
      {"name": "boolean3 package for R", "value": 3938, "url": "http://polisci.osu.edu"}
     ]
    },
    {
     "name": "Courses",
     "children": [
      {"name": "PS 4781", "value": 3938, "url": "http://polisci.osu.edu"},
      {"name": "PS 867", "value": 743, "url": "http://polisci.osu.edu"},
      {"name": "PS 846", "value": 743, "url": "http://polisci.osu.edu"}
     ]
    }
   ]    
  }
 ]
}
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="http://d3js.org/d3.v2.min.js" charset="utf-8"></script>
function accumulate(d) {
    return (d._children = d.children)
    ? d.value = d.children.reduce(function(p, v) { return p + accumulate(v); }, 0)
    : d.value;
  }

var g = g1.selectAll("g")
      .data(d._children)   // from d.children to d._children
      .enter().append("g");