iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 26
0
Data Technology

讓你資料美美的(d3.js+vue.js)系列 第 26

D3 force

Force-Directed

不知道這種圖有沒有正式的中文名稱?
https://ithelp.ithome.com.tw/upload/images/20180115/20105602gQdL2EaPdv.jpg
這個圖可以用來表達點與點之間的關係


畫Force-Drected graph需要使用d3中的力模擬器d3.forceSimulation,一個新的模擬器中要定義3個東西(參考)
link:連結的引力
charge:點之間的引力
center:引力的中心


var simulation = d3.forceSimulation()
	.force("link", d3.forceLink())
    .force("charge", d3.forceManyBody())
    .force("center", d3.forceCenter(width / 2, height / 2));

繪製點、線、文字

var link = svg.append("g")
	.attr("class", "links")
	.selectAll("line")
	.data(links)
	.enter().append("line")
	.attr("stroke-width", 5)
	.attr("stroke","black");

var node = svg.append("g")
	.attr("class", "nodes")
	.selectAll("circle")
	.data(map)
	.enter().append("circle")
	.attr("r", 8)
	.attr("fill", function(d,i) { return color(i); })
	.attr('stroke','white')
	.attr('stroke-width',2)
	.call(d3.drag()
		.on("start", dragstarted)
		.on("drag", dragged)
		.on("end", dragended));

var text = svg.selectAll("text")
     .data(map)
     .enter()
     .append("text")
     .style("fill", "black")
     .attr("dx", 12)
     .attr("dy", 5)
     .text(function(d){
        return d.name;
     });

將模擬器綁定節點、線、文字

simulation
	.nodes(map)           //產生index,vx,xy,x,y數值來做視覺化
	.on("tick", ticked);  //tick為模擬器的計時器,用來監聽綁定後數據的改變

simulation.force("link")
	.links(links)
	.distance(50);

定義ticked(),用來當tick發現數據改變時,要做的動作

function ticked() {
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; });

text
	.attr("x", function(d) { return d.x;})
	.attr("y", function(d) { return d.y;});
};

定義拖拉的動作,因為在拖拉的過程中,會中斷模擬器,所以利用restart來重啟

function dragstarted(d) {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}

function dragged(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;
}

function dragended(d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}

demo & code:https://codepen.io/FanWay/pen/PEBbqO


上一篇
D3圓餅圖
下一篇
D3 tree
系列文
讓你資料美美的(d3.js+vue.js)30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言