此代码适用于d3.js版本2但是,我在标题中指定的版本4中出现强制错误。我试过调查但是,我无法得到任何解决方案。下面是我的代码的脚本部分。我从这个链接中获取了参考:http://bl.ocks.org/jose187/4733747
<script>
function colores_google(n) {
var colores_g = ["yellow", "#dc3912", "#ff9900", "#109618", "#990099", "#0099c6", "#dd4477", "#66aa00", "#b82e2e", "#316395", "#994499", "#22aa99", "#aaaa11", "#6633cc", "#e67300", "#8b0707", "#651067", "#329262", "#5574a6", "#3b3eac"];
return colores_g[n % colores_g.length];
}
var width = 960,
height = 800
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g");
var force = d3.layout.force()
.gravity(.05)
.distance(400)
.charge(-100)
.size([width, height]);
d3.json("graphFile.json", function(json) {
force
.nodes(json.nodes)
.links(json.links)
.start();
var link = svg.selectAll(".link")
.data(json.links)
.enter()
.append("line")
.attr("class", "link")
.style('stroke', 'grey')
.style("stroke-width", function(d) { return Math.sqrt(d.weight); });
var node = svg.selectAll(".node")
.data(json.nodes)
.enter()
.append("g")
.attr("class", "node")
.call(force.drag);
node.append("circle")
.attr("r",function(d){
return d.radius * 5;
})
.style("fill", function(d,i) { return colores_google(i); } );
node.append("text")
.attr("dx", 12)
.attr("dy", ".35em")
.style('color', 'darkOrange')
.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("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
});
node.on('mouseover', function(d) {
link.style('opacity', function(l) {
if (d === l.source || d === l.target)
return 1;
else
return 0.1;
});
});
node.on('mouseout', function() {
link.style('opacity', 1);
});
});
</script>