【发布时间】:2014-05-21 15:25:20
【问题描述】:
我正在尝试在 D3 中构建一个力有向图。这是它的代码 -
index.html
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.node {
stroke: #FFFF;
stroke-width: 1.5px;
}
.link {
stroke: #111;
}
</style>
<body>
<h1>Hello there</h1>
<script src="d3.v3.min.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("copy.json", function(error, graph) {
force
.nodes(graph.nodes)
.links(graph.links)
.start();
var link = svg.selectAll(".link")
.data(graph.links)
.enter().append("line")
.attr("class", "link")
.style("stroke-width", function(d) { console.log(d.value); return d.value; });
var node = svg.selectAll(".node")
.data(graph.nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 10)
.style("fill", function(d) { console.log(d.name); return color(d.group); })
.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; });
});
});
</script>
</body>
</html>
此代码适用于 copy.json 文件。我只是将 here 中的 json 复制粘贴到该文件中。我试图通过解析一个txt文件来创建我自己的json。当我使用我的 json 文件时,相同的代码给了我错误。这是我的 json 文件(其中的一部分) -
{
"nodes":[
"group": 5,
"name": "Nancie"
},
{
"group": 5,
"name": "Jonell"
}
],
"links": [
{
"source": 1,
"target": 29,
"value": 2
},
{
"source": 1,
"target": 43,
"value": 3
}
]
}
我已经在 jsonlint 上测试了这个 json。换行符有区别吗?我确实阅读了一些关于这个的答案,但没有一个匹配。我的源节点和目标节点在范围内,我没有空值,并且我在创建 JSON 时处理了这种情况。
【问题讨论】:
-
您发布的代码中没有
weight的实例? -
@RUJordan - 那么这段代码是如何用于 copy.json 文件的呢?我从上述来源复制的json?
-
你真的只使用这两个链接和节点吗?因为您的链接引用索引为 29 和 43 的节点,并且这些节点未定义,所以当 d3 尝试查找这些节点的属性时,您将收到错误消息。
-
@AmeliaBR - 我拥有的 json 文件很大。所以我没有在问题中复制/粘贴所有内容。我确实意识到有人会认为这可能是错误的。所以我对我的问题做了一些修改。
标签: javascript json d3.js