0

So I working on the iteration of inserting information into a circle object to display.

<script type="text/javascript">
var data = d3.json("example.json", function(error, data){
    console.log("I'm working");
    console.log(data);
    var svg = d3.select("svg");
    console.log(data.length);
    for (i = 0; i < data.length; i ++) {
        svg.append("circle")
            .attr("cx", Math.random()*500)
            .attr("cy", Math.random()*500)
            .attr("r", 25)
            .attr("fill", "red")
            .append("text")
            .text(function(d) { return data[i].name } )
            .attr('dx', function(d) {return '1em';})
    .attr('dy', function(d) {return (0.08*this.parentNode.getBBox().height/2 + 0.5)+'em';})
    }
    svg.selectAll("circle").attr("fill", "red");
    svg.selectAll("text").attr("fill", "black")
})

so far I have attached the information to each circles. However I still cannot display the name of the objects I have no idea how to about showing connections through the data.

  • This is not the right way to work with d3. The linked question is actually quite good and will hopefully help you understand how to use d3 correctly. There is also this tutorial which coincidentally is also about circles: http://bost.ocks.org/mike/circles/. tl;dr: Bind the data, don't iterate yourself. – Felix Kling Jun 21 '15 at 19:09

1 Answers1

0

you can't define your text callback like this.

.text(function(d) { return data[i].name } )

By doing that, i will always set to 10 because it's the value at the end of your for loop and you dosen't seem to change it after. You have many solution the following isn't the best but should work, a cleaner solution can be founded with d3 docs and using d parameter in callback.

.text(function(d) { return data[this.i].name }.bind({i : i}) )
Payou
  • 371
  • 2
  • 7