1.diagonal生成器
diagonal生成器是路徑生成器的一種,需要的數據形式是
var data = [
{A:{x:100,y:100},
B:{x:200,y:200}},
{A:{x:200,y:200},
B:{x:300,y:100}},
];
上邊的相當於一條diagonal線條,通過source和target訪問器我們可以深入到內部,靈活指定x,y的座標
var diagnal = d3.svg.diagonal()
.source(function(d,i){ //自定義訪問器函數,但其實我們一般在數據中target source
return d.A;
})
.target(function(d,i){
return d.B;
});
2.cluster佈局
cluster佈局,pie佈局,chord佈局他們的作用一樣,我們用佈局將數據包裹,會生成線生成器所需要的數據
//root是傳進來的數據
var nodes = cluster.nodes(root); //生成節點對象
var links = cluster.links(nodes);//連線對象
console.log(nodes);
console.log(links);
nodes
links
nodes字典中有children,depth,name,x,y,5個一級屬性,在children字段內還有二級屬性,指出了children都有哪些結點
links字典中,source與target爲他的一級屬性,source中種屬性與上邊每個nondes的字段一樣,因爲每個source也是一個點。
最後,有了source與target就有了diagonal路徑生成器所需要的數據,就可以生成diagonal線條了。而nodes中有x,y座標我們就可以將數據綁定在circl上了,設定circle的座標大小等等。
—-讀取文件數據格式:
{
"name":"中國",
"children":
[
{
"name":"浙江" ,
"children":
[
{"name":"杭州" },
{"name":"寧波" },
{"name":"溫州" },
{"name":"紹興" }
]
},
{
"name":"廣西" ,
"children":
[
{"name":"桂林"},
{"name":"南寧"},
{"name":"柳州"},
{"name":"防城港"}
]
},
{
"name":"黑龍江",
"children":
[
{"name":"哈爾濱"},
{"name":"齊齊哈爾"},
{"name":"牡丹江"},
{"name":"大慶"}
]
},
{
"name":"新疆" ,
"children":
[
{"name":"烏魯木齊"},
{"name":"克拉瑪依"},
{"name":"吐魯番"},
{"name":"哈密"}
]
}
]
}
3.完整代碼
<style>
.node circle {
fill: #fff;
stroke: steelblue;
stroke-width: 1.5px;
}
.node {
font: 12px sans-serif;
}
.link {
fill: none;
stroke: #ccc;
stroke-width: 1.5px;
}
</style>
</head>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var width = 500,
height = 500;
var cluster = d3.layout.cluster()
.size([width, height - 200]);
var diagonal = d3.svg.diagonal()
.projection(function(d) { return [d.y, d.x]; })
// .source(function(d,i){
// return [d.source.y,d.source.x];
// })
// .target(function(d,i){
// return [d.target.y,d.target.x];
// })
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(40,0)");
d3.json("city.json", function(error, root) {
var nodes = cluster.nodes(root); //生成節點對象
var links = cluster.links(nodes);//連線對象
console.log(nodes);
console.log(links);
var link = svg.selectAll(".link")
.data(links)
.enter()
.append("path")
.attr("class", "link")
.attr("d", diagonal);
var node = svg.selectAll(".node")
.data(nodes)
.enter()
.append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })
node.append("circle")
.attr("r", 4.5);
node.append("text")
.attr("dx", function(d) { return d.children ? -8 : 8; })
.attr("dy", 3)
.style("text-anchor", function(d) { return d.children ? "end" : "start"; })
.text(function(d) { return d.name; });
});
</script>
最後效果: