我有以下json:
"Links": [
{"Source": "A","Target": "B","Value": "10000"},
{"Source": "A","Target": "C","Value": "10000"},
{"Source": "B","Target": "D","Value": "10000"}
]
如何提取唯一节点名称以在d3js强制布局图中使用它们。
尝试调整http://plnkr.co/edit/20t4F02vsM1U55ktCv66?p=preview。
非常感谢,
Marv
答案 0 :(得分:0)
尝试如下所示。
var graph = {
"Links": [
{"Source": "A","Target": "B","Value": "10000"},
{"Source": "A","Target": "C","Value": "10000"},
{"Source": "B","Target": "D","Value": "10000"}
]
};
var nodeArr = graph.Links.map(function(d){ return [d.Source,d.Target] }).join().split(",");
var uniqueNodeArr = nodeArr.filter(function(d,i){ return nodeArr.indexOf(d)==i });
graph['Nodes'] = uniqueNodeArr.map(function(node,i){ return { name: node, id: i }; });
graph['Links'] = graph['Links'].map(function(l){
var link = {};
link['source'] = uniqueNodeArr.indexOf(l.Source);
link['target'] = uniqueNodeArr.indexOf(l.Target);
link['value'] = l.Value;
return link;
});
var width = 960,
height = 500;
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);
svg.append("svg:defs").append("svg:marker")
.attr("id", "arrow")
.attr("viewBox", "0 -5 10 10")
.attr("refX", 15)
.attr("refY", -1.5)
.attr("markerWidth", 6)
.attr("markerHeight", 6)
.attr("orient", "auto")
.append("svg:path")
.attr("d", "M0,-5L10,0L0,5");
force
.nodes(graph.Nodes)
.links(graph.Links)
.linkDistance(60)
.start();
var link = svg.selectAll(".link")
.data(graph.Links)
.enter().append("path")
.attr("class", "link")
.style("stroke-width", "2")
.attr("marker-end", "url(#arrow)");;
var node = svg.selectAll(".node")
.data(graph.Nodes)
.enter()
.append("g")
.attr("class", "node");
node.append("circle")
.attr("r", 10)
.style("fill","red")
.call(force.drag);
node.append("text")
.attr("dx", 12)
.attr("dy", ".35em")
.text(function(d) { return d.name; });
force.on("tick", function() {
link.attr("d", function(d) { return "M"+d.source.x+","+d.source.y+" L"+d.target.x+","+d.target.y; });
node.attr("transform", function(d) { return "translate("+d.x+","+d.y+")"; });
});

.node {
stroke: #fff;
stroke-width: 1.5px;
}
.link {
stroke: #999;
stroke-opacity: .6;
}
text{
stroke: black;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
&#13;