【D3.js資料視覺化系列教程】(二十四)--力導向圖
阿新 • • 發佈:2019-02-17
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>testD3-22-force.html</title>
<script type="text/javascript" src="d3.js"></script>
<style type="text/css">
</style>
</head>
<body>
<script type="text/javascript" >
var h=300;
var w=300;
// 顏色函式
var colors=d3.scale.category20()//建立序數比例尺和包括20中顏色的輸出範圍
//(1)定義節點和聯絡物件陣列
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}
]
};
//(2)轉化資料為適合生成力導向圖的物件陣列
var force=d3.layout.force()
.nodes(dataset.nodes)//載入節點資料
.links(dataset.edges)//載入邊資料
.size([w,h])//設定有效空間的大小
.linkDistance(50)//連線的長度
.charge(-200)//負電荷量,相互排斥設定的負值越大越排斥
.start();//設定生效
var svg=d3.select("body")
.append("svg")
.attr("width",w)
.attr("height",h);
//(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)
.enter()
.append("circle")
.attr("r",function(d){//設定圓點的半徑,圓點的度越大weight屬性值越大,可以對其做一點數學變換
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>