我正在玩从零开始在D3中创建一个家谱,我无法将图表的节点分配到相应的出生年份。我将轴放在树图下面,但希望看到节点具有不同的链接长度。
JS:
var familyTree =
{'name':'Child', 'born':1990, 'parents': [
{'name':'Father', 'born':1970, 'parents': [
{'name':'GrandMother1', 'born':1950},
{'name':'GrandFather1', 'born':1940}]},
{'name':'Mother', 'born':1960, 'parents':[
{'name':'GrandFather2', 'born':1930},
{'name':'GrandMother2', 'born':1945}]}
]};
var margin = {top:20, right:90, bottom:30, left:90},
width = 900 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
var treemap = d3.tree()
.size([height,width]);
var nodes = d3.hierarchy(familyTree, function(d){
return d.parents;
});
nodes = treemap(nodes);
var svg = d3.select('body').append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom),
g = svg.append('g')
.attr('transform','translate(' + margin.left + ',' + margin.top + ')');
var formatNumber = d3.format('');
var x = d3.scaleLinear()
.domain([2017,1900])
.range([0,width]);
var xAxis = d3.axisBottom(x)
.ticks(25)
.tickFormat(formatNumber);
g.append('g')
.attr('transform','translate(0,' + height + ')')
.call(customXAxis);
function customXAxis(g) {
g.call(xAxis);
g.select('.domain').remove();
};
var link = g.selectAll('.link')
.data(nodes.descendants().slice(1))
.enter().append('path')
.attr('class','link')
.attr('d', function(d) {
return 'M' + d.y + ',' + d.x
+ 'C' + (d.y + d.parent.y) / 2 + ',' + d.x
+ ' ' + (d.y + d.parent.y) / 2 + ',' + d.parent.x
+ ' ' + d.parent.y + ',' + d.parent.x;
});
var node = g.selectAll('.node')
.data(nodes.descendants())
.enter().append('g')
.attr('class',function(d){
return 'node' +
(d.parents ? ' node--internal' : ' node--leaf');})
.attr('transform',function(d) {
return 'translate(' + d.y + ',' + d.x + ')';});
node.append('circle')
.attr('r',10);
node.append('text')
.attr('dy','.35em')
.attr('x',function(d){return d.parents ? -13 : 13;})
.style('text-anchor',function(d){
return d.parents ? 'end' : 'start';})
.text(function(d){return d.data.name;});
有人可以告诉我如何让节点X的位置代表出生年份吗?
答案 0 :(得分:0)
我能够通过调整链接和节点附加来解决问题,以使用born属性而不是y属性。 Working Fiddle
部分已更新:
var link = g.selectAll('.link')
.data(nodes.descendants().slice(1))
.enter().append('path')
.attr('class','link')
.attr('d', function(d) {
return 'M' + x(d.data.born) + ',' + d.x
+ 'C' + (x(d.data.born) + x(d.parent.data.born)) / 2 + ',' + d.x
+ ' ' + (x(d.data.born) + x(d.parent.data.born)) / 2 + ',' + d.parent.x
+ ' ' + x(d.parent.data.born) + ',' + d.parent.x;
});
var node = g.selectAll('.node')
.data(nodes.descendants())
.enter().append('g')
.attr('class',function(d){
return 'node' +
(d.parents ? ' node--internal' : ' node--leaf');})
.attr('transform',function(d) {
return 'translate(' + x(d.data.born) + ',' + d.x + ')';});