在前一个元素的每个x轴坐标位置之后追加具有可变宽度的元素(rect)

时间:2017-06-12 16:35:57

标签: d3.js

我想在前一个元素x轴坐标之后准确追加每个rect元素。我目前的代码是:

var data = [50,100,150]

var svg = d3.select("#bar_chart")
.append("svg")
    .attr("width", "1000")
    .attr("height", "500")

var rect = svg.selectAll("rect")
    .data(data)
    .enter().append("rect")
        .attr("x", function(d) { return (d * i) })
        .attr("y", "300")
        .attr("width", function(d, i){ return d})
        .attr("height", function(d, i){ return d})
        .attr("fill", "blue")
        .each(function(d, i) {console.log(i.x)})

其中给出以下内容: Code with x-axis position set to return (d * i)

我想要什么: Code with x-axis from each element start immediately after the previous one

提前致谢

2 个答案:

答案 0 :(得分:1)

您需要在当前宽度之前添加所有宽度。

https://jsfiddle.net/8dv1y74e/

var data = [50,100,150]

var svg = d3.select("#bar_chart")
.append("svg")
    .attr("width", "1000")
    .attr("height", "500")

var rect = svg.selectAll("rect")
    .data(data)
    .enter().append("rect")
        .attr("x", getPreviousWidths)
        .attr("y", "300")
        .attr("width", function(d, i){ return d})
        .attr("height", function(d, i){ return d})
        .attr("fill", "blue")
        .each(function(d, i) {console.log(i.x)})

function getPreviousWidths(d,i){
    return data.slice(0,i).reduce((memo,num)=>num+memo,0)
}

答案 1 :(得分:1)

另一个答案的替代方法,您可以使用变量来跟踪最近的矩形的x坐标,每次附加矩形时都添加它:



var data = [50,100,150];

var svg = d3.select("body")
.append("svg")
    .attr("width", "500")
    .attr("height", "500");

var positionX = 0; // where we are on the x axis, first element should be at 0 pixels.

var rect = svg.selectAll("rect")
    .data(data)
    .enter().append("rect")
        .attr("x", function(d) { 
                  var x = positionX;  // The x value for this rectangle
                  positionX = d + x;  // The x value for the next rectangle
                  return x;           // Return the x value for this rectangle.
         })
        .attr("y", "10")
        .attr("width", function(d, i){ return d})
        .attr("height", function(d, i){ return d})
        .attr("fill", "blue");

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
&#13;
&#13;
&#13;