Reputation: 109
how can I draw five rows of circles in D3?
° ° ° ° ° ° ° ° ° ° ° ° °
° ° ° ° ° ° ° ° ° ° ° ° °
° ° ° ° ° ° ° ° ° ° ° ° °
° ° ° ° ° ° ° ° ° ° ° ° °
° ° ° ° ° ° ° ° ° ° ° ° °
My HTML
<body>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="355px" height="355px" viewBox="0 0 351 351" enable-background="new 0 0 351 351" xml:space="preserve">
<g id="graph">
</g>
</svg>
I started like this:
var svg = d3.select("svg");
var g = svg.select("#graph");
var rectValues = [0, 17, 34, 51, 68, 85, 102, 119, 136, 153, 170, 187, 204, 221, 238, 255, 272, 289, 306, 323];
var rect = d3.select("body").select("svg").select("#graph").selectAll("rect")
.data(rectValues);
rect.enter().append("rect")
.attr("rx",100)
.attr("ry",100)
.attr("x", function(d) { return d })
.attr("y", ???)
.attr("width",15)
.attr("height",15);
But I do not know if I have to include more than one array(data) "even if x and y are the same values"?
Thats my fist version. It works(!) but it is not really a efficient version for the further purpose.
var rectX;
var rectY = 5;
var svg = d3.select("svg");
var g = svg.select("#graph");
for (var index1 = 0; index1<20; ++index1){
rectX = 5;
for (var index2 = 0; index2<20; ++index2) {
d3.select("body").select("svg").select("#graph").append("rect")
.attr("rx",100)
.attr("ry",100)
.attr("x", rectX)
.attr("y", rectY)
.attr("width",15)
.attr("height",15)
rectX=rectX+17;
}
rectY=rectY+17;
}
Upvotes: 3
Views: 699
Reputation: 32327
Since the circles have to come one below the other the x should not be:
var rectValues = [0, 17, 34, 51, 68, 85, 102, 119, 136, 153, 170, 187, 204, 221, 238, 255, 272, 289, 306, 323];
It should be
var rectValues = [0, 17, 34, 51, 68, 0, 17, 34, 51, 68,0, 17, 34, 51, 68,0, 17, 34, 51, 68,0, 17, 34, 51, 68,];
Here i am repeating the x values after 5 points, the reason is 6th circle should come below the 1st circle and 12th circle should come below 6th circle. So the 1st circle, 6th circle 12th circle. 18th circle ... all have same x value.
Note: In D3 the data drives the Document(DOM) so the name Data Driven Document (D3).
Make a variable yPos
var yPos = 20;
Make circles like this:
d3.select("body").select("svg").select("#graph").selectAll("rect")
.data(rectValues);
rect.enter().append("rect")
.attr("rx",100)
.attr("ry",100)
.attr("x", function(d) { return d })
.attr("y", function(d, i) { return (yPos * parseInt(i/5)) })
.attr("width",15)
.attr("height",15);
See this line
.attr("y", function(d, i) { return (yPos * parseInt(i/5)) })
Here i
is the index of the array element under process. So this parseInt(i/5)
is going to give me the column index (Thus you don't need a loop like you have mentioned in the ticket).
Full working code here
Hope this helps!
Upvotes: 3