我正在尝试建立一个互动的人口金字塔。我想更新条的宽度。
虽然有些东西不符合我的选择。凹形和凹形条形图更新为相同的宽度,因为它们接收相同的原点。我怀疑它与我选择或加入数据的方式有关。我已经尝试了几种组合,现在我很难阅读select和selectAll上的文档。
对此处出现问题的任何评论都非常感谢。
代码(here is the fiddle):
var pyramidCanvas = d3.select("body")
.append("svg")
.attr("width",200)
.attr("height",100);
var pyramidHeight = 100;
var pyramidWidth = 100;
var pyramidBarsRight, pyramidBarsLeft;
function setupPyramid(){
var data = [300,20,40,50,10];
var pyramidHeight = 100;
var pyramidWidth = 100;
var xScale = d3.scale.linear()
.domain([0,d3.max(data,function(d){return d;})])
.range([0,pyramidWidth]);
var barHeight = pyramidHeight/data.length;
console.log(barHeight);
pyramidBarsLeft = pyramidCanvas.selectAll("g-female")
.data(data)
.enter()
.append("g")
.attr("transform",function(d,i){return "translate(0,"+ (i * 10)+ ")" ;});
pyramidBarsLeft.append("rect")
.attr("class","female-bar")
.attr("x",function(d){return pyramidWidth-xScale(d);})
.attr("y",function(d,i){
return i*10;
})
.attr("width",function(d){console.log(d);return xScale(d);})
.attr("height",10)
.style("fill","pink");
pyramidBarsRight = pyramidCanvas.selectAll("g-male")
.data(data)
.enter()
.append("g")
.attr("transform",function(d,i){return "translate(0,"+ (i * 10)+ ")" ;});
pyramidBarsRight.append("rect")
.attr("class","male-bar")
.attr("x",pyramidWidth)
.attr("y",function(d,i){
return i*10;
})
.attr("width",function(d){console.log(d);return xScale(d);})
.attr("height",10)
.style("fill","steelblue");
}
function updatePyramid(data){
var femData = data.slice(0,5);
var malData = data.slice(5,9);
console.log(femData);
console.log(malData);
console.log(pyramidBarsRight.selectAll("rect"));
var xScale = d3.scale.linear()
.domain([0,d3.max(data,function(d){return d;})])
.range([0,pyramidWidth]);
pyramidBarsLeft
.selectAll(".female-bar")
.data(femData)
.transition()
.duration(500)
.attr("x",function(d){return pyramidWidth-xScale(d);})
.attr("width",function(d){console.log(d);return xScale(d);})
pyramidBarsRight
.selectAll(".male-bar")
.data(malData)
.transition()
.duration(500)
.attr("width",function(d){console.log(d);return xScale(d);});
}
setupPyramid();
updatePyramid([20,10,50,100,600,30,22,54,91,19,10]);
答案 0 :(得分:1)
您不应该保存enter
选择的结果并将其用作这样。从画布中选择它可以正常工作,请参阅here。原因是,一旦添加了DOM元素,enter
选择中的元素就会合并到update
选择中。