树状图(竖着)
d3.json("city.json", function (err, data) {
const width = 700, height = 800, padding = {top: 60, left: 30};
const svg = d3.select("body").append("svg")
.attr("width", width + padding.left * 2)
.attr("height", height + padding.top * 2).append("g")
.attr("transform", "translate(40,50)");
const tree = d3.layout.tree()
.size([width, height - 200])
.separation(function (a, b) {
//点与点之间的间隔比例
return a.parent === b.parent ? 1: 2;
});
// nodes:
// [{name: "中国",
// children: Array(3),
// depth: 0,
// x: 350,
// y: 0}
// ,...]
const nodes = tree.nodes(data);
// links:
// [
// {source:node,
// target:node}
// ,...]
const color = d3.scale.category20();
const links = tree.links(nodes);
const diagonal = d3.svg.diagonal()
.projection(function (d) {
return [d.x, d.y]
});
const link = svg.selectAll(".link")
.data(links)
.enter()
.append("path")
.attr("class", "link")
.attr("d", diagonal)
.attr("fill", "none")
.attr("stroke", "purple")
.attr("stroke-width", 2);
const node = svg.selectAll(".node")
.data(nodes)
.enter()
.append("g")
.attr("class", "node")
.attr("transform", function (d) {
return "translate(" + d.x + "," + d.y + ")";
});
node.append("circle")
.attr("r", 4.5)
.attr("fill",function (d,i) {
return color(i);
});
node.append("text")
.attr("dy", function (d) {
return d.children ? -14 : 20;
})
.style("text-anchor","middle")
.text(function (d) {
return d.name;
})
})
结果:
竖着
横着
d3.json("city.json", function (err, data) {
const width = 700, height = 600, padding = {top: 60, left: 30};
const svg = d3.select("body").append("svg")
.attr("width", width + padding.left * 2)
.attr("height", height + padding.top * 2).append("g")
.attr("transform", "translate(100,0)");
const tree = d3.layout.tree()
.size([width, height - 200])
.separation(function (a, b) {
console.log(a);
console.log(b);
return a.parent === b.parent ? 1 : 2;
});
// nodes:
// [{name: "中国",
// children: Array(3),
// depth: 0,
// x: 350,
// y: 0}
// ,...]
const nodes = tree.nodes(data);
// links:
// [
// {source:node,
// target:node}
// ,...]
const links = tree.links(nodes);
const diagonal = d3.svg.diagonal()
.projection(function (d) {
return [d.y, d.x]
});
const link = svg.selectAll(".link")
.data(links)
.enter()
.append("path")
.attr("class", "link")
.attr("d", diagonal)
.attr("fill", "none")
.attr("stroke", "purple")
.attr("stroke-width", 2);
const 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;
})
})
结果:
横着