Imi
Imi

Reputation: 549

How to append circles to the rows starting from the bottom?

I am trying to create boxes with circles in a row of 10x10. The first layer is of gray circles which is fine but the second layer of pink circles should be at the bottom like the image below:

output

but I can only start the circles from the top like so:

enter image description here

complete code (plunker):


 var circle = svgContainer
          .selectAll('path')
          .data(function() {
            var data = []
            for (var i = 0; i < 100; i++) {
              data.push(i)
            }
            return data
          })
          .enter()

        var circleAppend = circle
          .append("circle")
          .style("stroke", "#fff")
          .style("fill", function(d) {
            return '#95a6b3';
          })
          .attr("cx", function(d, i) {
            return i % 10 * rectWidth / 15 + 15
          })
          .attr("cy", function(d, i) {
            return Math.floor(i / 10) % 10 * rectWidth / 15 + 20
          })
          .attr("r", '0.4em');

        var arr = [];
        for (var i = 0; i < data.data; i++) {
          arr.push(1)
        }




        var circle2 = svgContainer
          .selectAll('path')
          .data(arr)
          .enter()


        var circle2Append = circle2
          .append('circle')
          .attr('class', 'circle2')
          .style("fill", function(d, i) {
            return '#dc0f6e';
          })
          .attr("cx", function(d, i) {
            return i % 10 * rectWidth / 15 + 15
          })
          .attr("cy", function(d, i) {
            return Math.floor(i / 10) % 10 * rectWidth / 15 + 20
          })
          .attr("r", '0.4em');

Upvotes: 1

Views: 268

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102218

You don't need two "enter" selections for the circles. Append a single selection of 100 circles, and use the index to set the colour:

.style("fill", function(d, i) {
    return i > limit ? '#dc0f6e' : '#95a6b3';
})

Here, for instance, the limit is the 68th circle:

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

var limit = 67;

var circles = svg.selectAll("foo")
    .data(d3.range(100))
    .enter()
    .append("circle")
    .style("stroke", "#fff")
    .style("fill", function(d, i) {
        return i > limit ? '#dc0f6e' : '#95a6b3';
    })
    .attr("cx", function(d, i) {
        return i % 10 * 20 + 20
    })
    .attr("cy", function(d, i) {
        return Math.floor(i / 10) % 10 * 20 + 20
    })
    .attr("r", '0.4em');
<script src="https://d3js.org/d3.v4.min.js"></script>

Upvotes: 1

Related Questions