I'm trying to create a fixed number of elements using D3, taking this value from a json file. This means that, if the given json data is n, I want to print n elements into my svg.
This is my code:
// Defining the size of the svg element
var w = 1000;
var h = 50;
// Defining the dataset
d3.json("people.json", function(dataset) {
// Iterating through the json
for(var i=0; i<dataset.length; i++) {
var svg = d3.select("body").append("svg")
.attr("width", w)
.attr("height", h);
// Iterating through the value
for(var j=0; j<dataset[i].age; j++) {
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("width", 20)
.attr("height", 20)
.attr("x", function(d, j) { return j * 55 })
}
}
});
This is my json example file (totally random values for ages):
[{
"name": "Larry",
"last": "Page",
"country": "USA",
"city": "Mountain View",
"age": 32
}, {
"name": "Sergey",
"last": "Bean",
"country": "USA",
"city": "Mountain View",
"age": 37
}, {
"name": "Bill",
"last": "Gates",
"country": "USA",
"city": "Seattle",
"age": 60
}, {
"name": "Mark",
"last": "Zuckemberg",
"country": "USA",
"city": "Palo Alto",
"age": 35
}, {
"name": "Sergio",
"last": "Marchionne",
"country": "Italy",
"city": "Milan",
"age": 65
}
]
My expected result should be something like that ( [-] --> svg rectangle)
Larry Page: [-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-]
Sergey Bean: [-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-][-]
and so on...
Can you help me to understand what I'm doing wrong?
Thanks!
.data(dataset)from rects drawing. That's misplaced there.selectAllis misplaced too, likeenter(). You only needappend("rect")and set its attributes.