/**
* Created by Silence_C on 2016/5/4.
*/
var width = 600,
height =400;
var svg = d3.select("body").append("svg")
.attr("width",width)
.attr("height",height)
.append("g");
var color = d3.scale.category20();
//数据转换
var partition = d3.layout.partition()
.sort(null)
.size([width,height])
.value(function(d){return 1})//表示分区大小的值。这里的意思是:如果数据文件中用 size 值表示结点大小,那么这里可写成 return d.size
//读取数据并绘图
d3.json("city.json",function(error,root){
if (error) console.log(error);
console.log(root);
var nodes = partition.nodes(root),
links = partition.links(nodes);
console.log(nodes);
开始画图
var rects = svg.selectAll("g")
.data(nodes)
.enter()
.append("g")
rects.append("rect")
.attr("x", function (d) {return d.x; })//顶点的x坐标
.attr("y",function(d){return d.y; })//顶点的y坐标
.attr("width", function (d) {return d.dx;}) //顶点的宽度dx
.attr("height",function(d){return d.dy;}) //顶点的高度dy
.style("stroke","#fff")
.style("fill",function(d){
return color((d.children ? d: d.parent).name);
})
.on("mouseover",function(d){
d3.select(this)
.style("fill","yellow")
})
.on("mouseout",function(d){
d3.select(this)
.transition()
.duration(200)
.style("fill",function(d){
return color((d.children?d: d.parent).name)
})
})
rects.append("text")
.attr("class","node_text")
.attr("transform",function(d,i){
return "translate("+( d.x+20)+","+ (d.y+20)+")"
})
.text(function (d,i) {
return d.name;
})
})