数据源:city.json:
{ "name":"中国", "children": [ { "name":"浙江" , "children": [ {"name":"杭州" }, {"name":"宁波" }, {"name":"温州" }, {"name":"绍兴" } ] }, { "name":"广西" , "children": [ { "name":"桂林", "children": [ {"name":"秀峰区"}, {"name":"叠彩区"}, {"name":"象山区"}, {"name":"七星区"} ] }, {"name":"南宁"}, {"name":"柳州"}, {"name":"防城港"} ] }, { "name":"黑龙江", "children": [ {"name":"哈尔滨"}, {"name":"齐齐哈尔"}, {"name":"牡丹江"}, {"name":"大庆"} ] }, { "name":"新疆" , "children": [ {"name":"乌鲁木齐"}, {"name":"克拉玛依"}, {"name":"吐鲁番"}, {"name":"哈密"} ] } ] }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>集群图</title> </head> <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> <body> <script src = "d3.js"></script> <script src = "js/cluster.js"></script> </body> </html>咳咳,开始干正事咯~!!!
一、绘制前的准备
(1)定义数据转换函数:cluster
var width = 500, height = 500; var cluster = d3.layout.cluster() .size([height,width-200]);(2)构造对角线生成器:diagonal,返回的函数会生成一条贝塞尔曲线,以此来连接source和target两端:
var diagonal = d3.svg.diagonal() .projection(function(d){return [d.y, d.x];}); //投影projection转换点位置,默认返回[d.x,d.y](3)老掉牙的操作:
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 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; });
//画线 var link = svg.selectAll(".link") .data(links) .enter() .append("path") .attr("class","link") .attr("d",diagonal); })