无法显示d3js树

时间:2016-03-05 20:49:58

标签: javascript d3.js

我正在尝试使用d3js创建一个树图,其中两个节点相互连接。我的JS如下:

bar.setMinimum(0);
bar.setMaximum((int)file.length());

try{
     while((check = reader.readLine()) != null){

         words = words + check + "\n";
         stringCount = words.getBytes();
         bar.setValue(stringCount.length);

     }      
  }catch(Exception e){}

  System.out.println(stringCount.length);
  System.out.println(file.length());

JS小提琴:https://jsfiddle.net/eeLfog4m/

不幸的是,页面上没有任何内容,我不确定为什么。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您的数据不像普通的树形布局那样设置。以评论中的Lars为例:http://bl.ocks.org/mbostock/4063550

数据如下:

{
 "name": "flare",
 "children": [
  {
   "name": "analytics",
   "children": [
    {
     "name": "cluster",
     "children": [
      {"name": "AgglomerativeCluster", "size": 3938},
      {"name": "CommunityStructure", "size": 3812},
      {"name": "HierarchicalCluster", "size": 6714},
      {"name": "MergeEdge", "size": 743}
     ]
    },
    {
     "name": "graph",
     "children": [
      {"name": "BetweennessCentrality", "size": 3534},
      {"name": "LinkDistance", "size": 5731},
      {"name": "MaxFlowMinCut", "size": 7840},
      {"name": "ShortestPaths", "size": 5914},
      {"name": "SpanningTree", "size": 3416}
     ]
    },.....

你确定你不想要力布局? :https://bl.ocks.org/mbostock/4062045

以下是您的数据的力量:https://jsfiddle.net/reko91/s6fug9q6/

var width = window.innerWidth;
var height = window.innerHeight;

var color = d3.scale.category20();

var nodes = [{"id":"1","name":"a"},{"id":"2","name":"b"}];
var links = [{"source":0,"target":1}];

var svg = d3.select("body").append("svg");
svg.attr("width", width);
svg.attr("height", height);
svg.append("svg:g");

var force = d3.layout.force()
    .charge(-120)
    .linkDistance(30)
    .size([width, height]);


  force
      .nodes(nodes)
      .links(links)
      .start();

  var link = svg.selectAll(".link")
      .data(links)
    .enter().append("line")
      .attr("class", "link")
      .style("stroke-width", function(d) { return Math.sqrt(d.value); });

  var node = svg.selectAll(".node")
      .data(nodes)
    .enter().append("circle")
      .attr("class", "node")
      .attr("r", 5)
      .style("fill", function(d,i) { return color(i); })
      .call(force.drag);

  node.append("title")
      .text(function(d) { return d.name; });

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

    node.attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; });
  });
.node {
  stroke: #fff;
  stroke-width: 1.5px;
}

.link {
  stroke: #999;
  stroke-opacity: .6;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

您可以明确定位这些节点。