赞
踩
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src="d3/d3.js"></script>
<script>
// nodes和edges是必备的两个属性。
// nodes中的数据是一个表示节点的对象数组;
// edges是一个表示边的对象数组,其中source和target子属性是必备的,其值代表了nodes数组中的索引。
// 节点和边数组都可以有额外的属性。
var w=300;
var h=300;
var colors=d3.scale.category20()
var dataset={
nodes:[//节点
{ name:"Adam"},
{ name:"Bob"},
{ name:"Carride"},
{ name:"Donovan"},
{ name:"Edward"},
{ name:"Felicity"},
{ name:"George"},
{ name:"Hannah"},
{ name:"Iris"},
{ name:"Jerry"}
],
edges:[//边
{ source:0,target:1,weight:1,color:1},
{ source:0,target:2,weight:3,color:4},
{ source:0,target:3,weight:4,color:6},
{ source:0,target:4,weight:6,color:65},
{ source:1,target:5,weight:3,color:76},
{ source:2,target:5,weight:8,color:879},
{ source:2,target:5,weight:7,color:989},
{ source:3,target:4,weight:9,color:643},
{ source:5,target:8,weight:1,color:54},
{ source:5,target:9,weight:3,color:54},
{ source:6,target:7,weight:4,color:45},
{ source:7,target:8,weight:0,color:43},
{ source:2,target:8,weight:8,color:243},
{ source:3,target:8,weight:1,color:43},
{ source:5,target:8,weight:5,color:13},
{ source:6,target:8,weight:3,color:351},
{ source:8,target:9,weight:4,color:1}
]
};
var svg=d3.select("body").append("svg").attr("width",w).attr("height",h)
//2.转化数据为适合生成力导向图的对象数组
var force=d3.layout.force()
.nodes(dataset.nodes)// 加载节点数据
.links(dataset.edges)//加载边数据
.size([w,h])//设置 有效空间的大小
.linkDistance(50)//连线的长度
.charge(-200)//负电荷量,相互排斥设置的负电荷量
.start()//启用力布局
//3.创建作为连线的SVG直线
var edges=svg.selectAll("line")
.data(dataset.edges)
.enter()
.append("line")
.style("stroke",function(d){//设置线的颜色
return colors(d.color)
})
.style("stroke-width",function(d,i){
return d.weight
//4.创建作为连线的SVG圆形
var nodes=svg.selectAll("circle")
.data(dataset.nodes)
.append("circle")
.attr("r",function(d){
return Math.log(d.weight)*10;
.style("fill",function(d){
return colors(d.weight*d.weight*d.weight)
.call(force.drag)
//5.打点更新
force.on("tick",function(){
//边
edges.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
//节点
nodes.attr("cx",function(d){
return d.x
}).attr("cy",function(d){
return d.y
</script>
</body>
</html>