

現在こちら( <http://qiita.com/tag1216/items/b7f846af66db30b8c393> )(
<http://qiita.com/tag1216/items/ad406625dc654d3c0982> )を参考にプログラムを作成しています。  
１つ目のurlを参考にはてなブックマーク版のプログラムを作成しました。  
以下がそのソースになります。

[code]

    <!DOCTYPE html>
    <html lang="ja">
    <style>
     svg {
        border: solid 1px;
    }
    .node circle {
        stroke: #000;
        stroke-width: .5px;
        opacity: .7;
    }
    .node text {
        pointer-events: none;
        font-size: 8px;
    }
    .node .shadow {
        stroke: #fff;
        stroke-width: 3px;
        stroke-opacity: .7;
    }
    .node .text {
    }
    .link {
        stroke: #888;
        opacity: .3;
    }
     </style>
    <head>
      <meta charset="utf-8">
      <title>D3.js(Force Layout)の練習</title>
    </head>
    <body>
      <script src="http://d3js.org/d3.v3.js" charset="utf-8"></script>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
    
    
    
      <script>
      function pointer(){
         var object = document.getElementById('object');
       if (object.contentDocument)
       var svgdoc = object.getSVGDocument();
       var svgelm = svgdoc.documentElement.style.cursor='pointer';
     }
    
    
      var w = 1024;
      var h = 800;
    
      var nodes = [];
      var links = [];
      var xlink = [];
      var link2 = [];
      var tags = [];
      var items = [];
      var Tag = [];
      var nodes2 = [];
      var links2 = [];
    
    
    
    
    
      var color = d3.scale.category20();
    
      var NAME_PREFIX = "_";
    
    
      /* var url = "https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=http://feeds.feedburner.com/hatena/b/hotentry&num=-1";
      var proxy_url = "http://allow-any-origin.appspot.com/" + encodeURIComponent(url); */
    
    
      function for_each(array, func){ Array.prototype.forEach.call(array, func); }
    
      function get_html(callback){
       var hatena_hotentry_url = "http://b.hatena.ne.jp/hotentry";
       hatena_hotentry_url = "http://allow-any-origin.appspot.com/"
        + encodeURIComponent(hatena_hotentry_url);
    
    
    
    
    
    
       /* var hatena_hotentry_url = "./hatena_hotentry.html" */
    
       var req = new XMLHttpRequest();
       req.open("GET", hatena_hotentry_url);
       req.onreadystatechange = function() {
        if (req.readyState === 4 && req.status === 200) {
         callback(req.responseText);
         req = undefined;
        }
       };
       req.send(null);
      }
    
      function html_to_relation(html){
       var doc = new DOMParser().parseFromString(html, "text/html");
       var error_tags = doc.getElementsByTagName("parsererror");
       if(error_tags.length){
        console.log("error: ", error_tags);
        return [["Parse error", "Maybe HTML is broken"]];
       }
    
       var relation = []; /*// [["name", ...], ...]
      */ var entry_elms = doc.querySelectorAll(
         "[data-track-section='default'] .entry-contents");
       for_each(entry_elms, function(entry_elm){
        var entry_link_elm = entry_elm.querySelector(".entry-link");
        if(!entry_link_elm){ return; }
    
        var name_array = [];
        relation.push(name_array);
         name_array.push(entry_link_elm.href);
        name_array.push(entry_link_elm.title);
    
    
    
        var entry_meta_elm = entry_elm.nextElementSibling;
        if(!entry_meta_elm){ return; }
        for_each(entry_meta_elm.querySelectorAll("a.tag"), function(tag_elm){
    
          name_array.push(tag_elm.textContent);
        });
    
    
       });
    
       return relation;
       }
    
    
    
    
    
    
      function relation_view(relation){
       /*document.getElementById("view").textContent
               = JSON.stringify(relation, undefined, 2);
      */
    
    
    
      /* d3.json(proxy_url,function(error,json){
      if(error){
       return console.warn(error);
      }
    
      var feeds = json.responseData.feed;
    
      for(var x = 0;x < feeds.entries.length;x++){
       var href = {"url": feeds.entries[x].link};
       xlink.push(href);
      };
    
      }); */
    
    
     var d = [];
     var normal = [];
    
       for(var i = 0;i<relation.length;i++){
          if(i+1 < relation.length){
              var num ={"source":  i ,"target": + (i+1) };
          }else{
              var num ={"source":  i , "target": 0};
          }
         /*  var list = {"label": relation[i][1]  , "url": relation[i][0],
                "tag":relation[i][2] +","+ relation[i][3] +","+ relation[i][4] +","+ relation[i][5]}; */
    
    
    
    
                var sub1 = relation[i][2];
                 var sub2 = relation[i][3];
                 var sub3 = relation[i][4];
                 var sub4 = relation[i][5];
    
    
    
                 var a1 = {"name":sub1,"url":'http://b.hatena.ne.jp/search/tag?q=' + sub1};
                 var a2 = {"name":sub2,"url":'http://b.hatena.ne.jp/search/tag?q=' + sub2};
                  var a3 = {"name":sub3,"url":'http://b.hatena.ne.jp/search/tag?q=' + sub3};
                 var a4 = {"name":sub4,"url":'http://b.hatena.ne.jp/search/tag?q=' + sub4};
                 var c = [];
                 c.push(a2,a3,a4);
                 normal.push(a2,a3,a4);
                 /*  a.push(sub1,sub2,sub3,sub4); */
    
    
          var list = {"label": relation[i][1]  , "url": relation[i][0],
          "tags":c};
    
           /* var subtags = {"tag":relation[i][2] + relation[i][3] + relation[i][4] + relation[i][5]}; */
    
        /*  var sub1 = relation[i][2];
         var sub2 = relation[i][3];
         var sub3 = relation[i][4];
         var sub4 = relation[i][5];
    
         var a = [];
         var supersub = {"tag":a};
         a.push(sub1,sub2,sub3,sub4);
    
    
    
    
         console.log(supersub); */
    
    
    
    
    
        /* a.name  = [sub1,sub2,sub3,sub4]; */
    
    
    
    
    
    
    
            nodes.push(list);
                 links.push(num);
    
    
    
       }
    
    
      console.log(nodes)
    
    
    
     var tags = nodes.reduce(function(tags,item){
        items.push(item);
        console.log(items)
         item.tags.forEach(function(tag){
       var name = NAME_PREFIX + tag.name;
        if(!(name in tags)){
         tags[name] = {
           name:tag.name,
           urlName:tag.url,
           count:0
         };
        }
        tags[name].count++;
       });
       return tags;
     },[]);
    
    
    
    
       var nodes2 = d3.values(tags)
          .sort(function(tag1,tag2){
          return tag1.count - tag2.count;
         });
      console.log(nodes2)
    
    
    
    
    
      var tagLinks = nodes.reduce(function(links,item){
         item.tags.forEach(function(tag1){
    
          item.tags.forEach(function(tag2){
           var key = tag1.name + NAME_PREFIX + tag2.name;
           if(!(key in links)){
            links[key] = {
              source:nodes2.indexOf(tags[NAME_PREFIX + tag1.name]),
              target:nodes2.indexOf(tags[NAME_PREFIX + tag2.name]),
              count:0
            };
           }
           links[key].count++;
          })
         })
         return links;
      },[]);
    
         console.log(tagLinks)
    
    
    
    
         var links2 = d3.values(tagLinks);
         console.log(links2)
        /*  var tags =  relation.reduce(function(tags,item){
        relation.forEach(function(tag){
         var name = NAME_PREFIX + tag;
         if(!(name in tags)){
          tags[name] = {
              name:tag,
              urlname:'http://b.hatena.ne.jp/search/tag?q=' + tag,
              count:0
          };
         }
         tags[name].count++;
        });
        return tags;
      },[]);
    
    
        var nodes = d3.values(tags)
          .sort(function(tag1,tag2){
          return tag1.count - tag2.count;
       });
     */
    
    
    
    
       /* var tagLinks = relation.reduce(function(links,item){
       relation.forEach(function(tag1){
        relation.forEach(function(tag2){
         var key = tag1.name + NAME_PREFIX + tag2.name;
        if(!(key in links)){
         links[key] = {
             source:nodes.indexOf(tags[NAME_PREFIX + tag1.name]),
             target:nodes.indexOf(tags[NAME_PREFIX + tag2.name]),
             count:0
         };
        }
        links[key].count++;
        })
       })
       return links;
      },[]); */
    
    
        /* var links = d3.values(tagLinks); */
    
    
    
    
    
    
    
    
    
    
         var force = d3.layout.force()
              .size([w, h])
              .linkStrength(1.0)
              .friction(0.1)
              .linkDistance(400)
              .charge(function(d){return -200;})
              .gravity(0.2);
    
    
        /*console.log(nodes)*/
    
        var svg = d3.select("body").append("svg").attr({width:w, height:h});
    
         /* var link = svg.selectAll("line")
              .data(links)
              .enter()
              .append("line")
              .style({stroke: "#ccc",
                      "stroke-width": 1}); */
    
    
    
             force
               .nodes(nodes2)
               .links(links2)
               .start();
    
    
             /* var link = svg.selectAll('.link')
               .data(links2)
               .enter()
               .append('line')
               .attr('class','link')
               .style({stroke: "#ccc",
                              "stroke-width": 1}); */
    
                var link = svg.selectAll('.link')
                          .data(links2)
                         .enter().append('line')
                          .attr('class', 'link')
                           .style('stroke-width', function(d) { return d.count * d.count; });
    
    
    
             var node = svg.selectAll('.node')
                .data(nodes2)
                .enter()
                .append('g')
                .attr('class','node')
                .call(force.drag);
    
             var a = node.append('a')
                .attr('xlink:href',function(d){return 'http://b.hatena.ne.jp/search/tag?q=' + d.name;})
                .attr('target','_blank');
    
    
             a.append('circle')
             .attr('r', function(d) { return 9 * Math.sqrt(d.count) })
             .style('fill', function(d) { return color(d.index); })
             .on('mouseover', function(d) { d3.select(this.parentNode.parentNode).style('z-index', 999); })
             .on('mouseout', function(d) { d3.select(this.parentNode.parentNode).style('z-index', null); })
    
         node.append('text')
             .attr('class', 'shadow')
             .attr('dx', 0)
             .attr('dy', '.5em')
             .style('font-size', function(d) { return (2*Math.sqrt(d.count)) + 'px' })
             .text(function(d) { return d.name + '(' + d.count + ')'; })
    
    
    
         node.append('title')
             .text(function(d) { return d.name + ':' + d.count; });
    
    
    
    
             /* /* var node = svg.selectAll("a")
         .data(nodes)
         .enter()
         .append("a")
         .attr("xlink:href",function(d){return d.url;})
         .attr('target','_blank')
         .append("circle")
         .attr({r:20,opacity:0.5})
    
         .style('fill',function(d){ return color(d.index);})
         .on('mouseover',function(d){d3.select(this.parentNode.parentNode).style('z-index',999);})
         .on('mouseout',function(d){d3.select(this.parentNode.parentNode).style('z-index',null);})
         .attr('class','node') */
    
    
    
        /*  .call(force.drag);
     */
    
         /* var label = svg.selectAll('text')
         .data(nodes)
         .enter()
         .append('text')
         .attr('class','shadow')
         .attr('dx',0)
         .attr('dy','.5em')
         .style({"font-size":5})
         .attr({"text-anchor":"middle",
             "fill":"black"})
    
         .text(function(d){return d.label;})
    
    
        node.append('title')
        .text(function(d){return d.label;}); */
    
    
    
         /* var label = svg.selectAll('text')
          .data(nodes)
          .enter()
          .append('text')
          .attr('class','shadow')
          .attr('dx',0)
          .attr('dy','5em')
          .attr({"text-anchor":"middle",
             "fill":"black"})
          .attr({'pointer-events' : 'none'})
          .style('font-size',function(d){ return (6* Math.sqrt(d.count)) + 'px'})
          .text(function(d){return d.label;}); */
    
    
    
    
          force.on("tick", function() {
         link.attr('x1', function(d) { return d.source.x; })
                .attr('y1', function(d) { return d.source.y; })
                .attr('x2', function(d) { return d.target.x; })
                .attr('y2', function(d) { return d.target.y; });
             /*  link.attr({x1: function(d) { return d.source.x; },
                         y1: function(d) { return d.source.y; },
                         x2: function(d) { return d.target.x; },
                         y2: function(d) { return d.target.y; }}); */
               node.attr('transform',function(d){return 'translate(' + d.x + ',' + d.y + ')'; });
              /* node.attr({cx: function(d) { return d.x; }
                         cy: function(d) { return d.y; }}); */
               /* label.attr({x: function(d) { return d.x;},
                   y: function(d) { return d.y }}); */
    
      })
      }
    
    
    
      get_html(function(html){ relation_view(html_to_relation(html)); });
    
    
    
    
    
    
    </script>
    </body>
    </html>
[/code]

１つ目の参考urlから２つ目のurlのプログラムのように書き換えを行いたいのですが、２つ目のurlの

[code]

    function appendItem(item) {
    items.push(item);
    nodes.push(item);
    item.tags.forEach(function(tag) {
        var name = "___" + tag.name;
        if (!(name in tags)) {
            tags[name] = tag;
            tags[name].count = 0;
            nodes.push(tags[name]);
        }
        tags[name].count++;
        links.push({
            source: nodes.indexOf(item),
            target: nodes.indexOf(tags[name])
        });
    });
    restart();
    
[/code]

}  
この部分の書き換えが上手くいきません。  
appendItemの要素にnodes配列を読み込ませたいのですが、どのようにすれば読み込ませることができるでしょうか？

恐縮ではございますが、お力添え宜しくお願い致します。


CC BY-SA 3.0
2015-12-12T08:09:03.210
19909
2015-12-13T11:39:44.137
2015-12-13T11:39:44.137
13172
13172
question
javascript d3.js
function appendItemの使い方について


d3.jsのForce
Layoutで使用するデータは次のような形式です（以下の例では`node1`と`node2`、また、`node1`と`node3`の間がリンクされます）。

[code]

    var nodes = [
      {"name": "node1"},
      {"name": "node2"},
      {"name": "node3"}
    ];
    
    var links = [
      {"source": 0, "target": 1},
      {"source": 0, "target": 2}
    ];
    
[/code]


CC BY-SA 3.0
2015-12-12T14:22:57.280
19919
2015-12-12T14:22:57.280
13493
19909
answer