javascript - D3.js Multiple Line Chart -
i tried show 2 line chart using d3.js,
i can display first chart "blob",
but doesn't work "blub"!!
how can fix , how simplify 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; (var 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>
first off, don't need loop here (you never in d3), 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 because you're selecting path
elements, which, after first iteration of loop, there already. is, data provide in .data()
matched existing path
element , hence .enter()
selection empty, adding nothing. can work around e.g. assigning class each path
allows distinguish them, better solution use nested selection i've outlined above.
complete demo here.
see this tutorial more details on how selections work.
Comments
Post a Comment