0

我正在尝试根据以下 JSON 文件在 D3 Javascript 库中绘制节点(圆圈):

{
 "nodes":[{"name":["Node1", "Node2", "Node3"]}, 
          {"name":["Node4"]},
          {"name":["Node5"]}]
}

这是我的代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sample2</title>
<style>

.node {
stroke: #fff;
stroke-width: 1.5px;
}

</style>
</head>
<body>

<script type="text/javascript" src="d3/d3.v3.js"></script>
<script>
var width = 960,
height = 500;
var color = d3.scale.category20();
var force = d3.layout.force()
.charge(-120)
.linkDistance(30)
.size([width, height]);

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

d3.json("folder/jsonsample.json", function(error, graph) {
force
.nodes(graph.nodes) 
.start();

 var node = svg.selectAll(".node")
    .data(graph.nodes)
    .enter().append("circle")
    .attr("class", "node")
    .attr("r", 10)
    .call(force.drag);

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

force.on("tick", function() {
node.attr("cx", function(d) { return d.x; })
    .attr("cy", function(d) { return d.y; });
});
});
</script> 
</body>
</html>

使用这个 HTML 文件,我只画了三个圆圈,因为代码是基于存在三个名称的事实。我想画五个节点(圆圈),因为我Node1, Node2, Node3, Node4 and Node5"name, name, and name". 谁能帮我画五个圆圈。非常感激你的帮助。

4

1 回答 1

1

也许您可以使用Collapsible Force Layout,请参阅mbostock 块中的示例。使用该示例和以下 json 文件(更改了他的 readme.json 文件):

{
 "name": "example",
 "children": [
  {
   "name": "group1",
   "children": [
      {"name": "node1", "size": 3000},
      {"name": "node2", "size": 3000},
      {"name": "node3", "size": 3000}
   ]
  },
  {
   "name": "node4", "size": 5000
  },
  {
    "name": "node5", "size": 10000
  }
 ]
}

你可以得到类似的东西。你得到一个有 3 个孩子的根元素,一个有 3 个节点。看在此处输入图像描述

如果您选择根节点,一切都会崩溃。

于 2013-11-14T08:58:47.717 回答