利用partition布局生成分区图
const width = 700, height = 500, padding = {top: 160, left: 130};
d3.json("city.json", function (error, data) {
const svg = d3.select("body").append("svg")
.attr("width", width + padding.left * 2)
.attr("height", height + padding.top * 2)
.append("g");
const partition = d3.layout.partition()
.sort(null)
.size([1000,height])
.value(d=>1);
const nodes = partition(data);
const links = partition.links(nodes);
const color = d3.scale.category20();
console.log(nodes);
console.log(links);
const gRects = svg.selectAll("g")
.data(nodes)
.enter()
.append("g");
gRects.append("rect")
.attr("x",d=>d.x)
.attr("y",d=>d.y)
.attr("width",d=>d.dx)
.attr("height",d=>d.dy)
.style("stroke","#FFF")
.style("fill",d=>color((d.children?d:d.parent).name))
gRects.append("text")
.attr("class","nodeText")
.attr("x",d=>d.x)
.attr("y",d=>d.y)
.attr("dx",d=>d.dx/2)
.attr("dy",20)
.text(d=>d.name)
});
结果:
圆形分区图
const svg = d3.select("body").append("svg")
.attr("width", width + padding.left * 2)
.attr("height", height + padding.top * 2)
.append("g")
.attr("transform","translate(400,350)");
const radius = 400;
const partition = d3.layout.partition()
.sort(null)
.size([2 * Math.PI, radius * radius])
.value(d => 1);
const nodes = partition(data);
const links = partition.links(nodes);
const color = d3.scale.category20();
console.log(nodes);
console.log(links);
const arcPath = d3.svg.arc()
.startAngle(d => d.x)
.endAngle(d => d.x + d.dx)
.innerRadius(d => Math.sqrt(d.y))
.outerRadius(d => Math.sqrt(d.y + d.dy));
const gArcs = svg.selectAll("g")
.data(nodes)
.enter()
.append("g");
gArcs.append("path")
.attr("display", d => d.depth ? null : "none")
.attr("d", arcPath)
.style("stroke", "#fff")
.style("fill", d => color((d.children ? d : d.parent).name));
gArcs.append("text")
.attr("class", "nodeText")
.attr("dy", ".5em")
.attr("transform", function (d, i) {
if (i !== 0) {
let r = d.x + d.dx / 2;
const angle = Math.PI / 2;
r += r < Math.PI ? (angle * -1) : angle;
r *= 180 / Math.PI;
return `translate(${arcPath.centroid(d)})rotate(${r})`
}
})
.text(d => d.name)
结果: