Reputation: 51
I tried to show my two Line Chart using D3.js,
I can display the first chart "blob",
But it doesn't work with "blub"!!
How can I fix it and how to simplify the for loop?
var canvas=d3.select("body")
.append("svg")
.attr("width",500).attr("height",300);
var donnees= {
blob:[
{x:10,y:20},{x:20,y:60}, {x:30,y:70},
{x:40,y:202},{x:50,y:260}, {x:60,y:70},
{x:70,y:75},{x:80,y:70}, {x:90,y:0}
],
blub:[
{x:100,y:20},{x:110,y:20},{x:120,y:60}, {x:130,y:70},
{x:140,y:32},{x:150,y:60}, {x:160,y:90},
{x:170,y:75},{x:180,y:100}, {x:190,y:20}
]
};
var groupe= canvas.append("g")
.attr("transform", "translate(20,20)");
var line= d3.svg.line()
.x (function(d){return d.x})
.y (function(d){return d.y});
var colors = d3.scale.category20();
var index = 0;
for (var i in donnees) {
groupe.selectAll("path")
.data([donnees[i]])
.enter()
.append("path")
.attr("d",line)
.attr("fill", "none")
.attr("stroke", colors(index))
.attr("stroke-width","1");
index++
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
Upvotes: 0
Views: 1040
Reputation: 109232
First off, you don't need a loop here (you almost never do in D3), but you can use nested selections:
groupe.selectAll("g")
.data(d3.values(donnees))
.enter()
.append("g")
.selectAll("path")
.data(function(d) { return [d]; })
.enter()
.append("path")
...
The problem you're seeing specifically is because you're selecting path
elements, which, after the first iteration of the loop, will be there already. That is, the data you provide in .data()
is matched by the existing path
element and hence the .enter()
selection is empty, adding nothing. You can work around this e.g. by assigning a class to each path
that allows you to distinguish them, but a better solution is to use nested selection as I've outlined above.
Complete demo here.
See this tutorial for more details on how selections work.
Upvotes: 1
Reputation: 169
Instead of using data() and enter(), i directly appended the path tag to g tag which worked for me.
var canvas=d3.select("body")
.append("svg")
.attr("width",500).attr("height",300);
var donnees= {
blob:[
{x:10,y:20},{x:20,y:60}, {x:30,y:70},
{x:40,y:202},{x:50,y:260}, {x:60,y:70},
{x:70,y:75},{x:80,y:70}, {x:90,y:0}
],
blub:[
{x:100,y:20},{x:110,y:20},{x:120,y:60}, {x:130,y:70},
{x:140,y:32},{x:150,y:60}, {x:160,y:90},
{x:170,y:75},{x:180,y:100}, {x:190,y:20}
]
};
var groupe= canvas.append("g")
.attr("transform", "translate(20,20)");
var line= d3.svg.line()
.x (function(d){ return d.x})
.y (function(d){return d.y});
var colors = d3.scale.category20();
var index = 0;
for (var i in donnees) {
groupe
.append("path")
.attr("d", line(donnees[i]))
.attr("fill", "none")
.attr("stroke", colors(index))
.attr("stroke-width", 1);
index++
}
Upvotes: 1