2016-08-11 4 views
0

Ich zeichne einige Svg-Linien in d3.js Ich habe es so eingerichtet, anstatt mit d3.svg.line() so dass jede Zeile getrennt ist und ich kann jeder eine eindeutige Klasse geben. Meine Zeilen werden jedoch nicht angezeigt, da sie nicht das y2-Attribut erhalten.Svg Zeilen in D3 von CSV (als separate Zeilen nicht eine einzige Zeile) - nicht angezeigt

Screenshot von der Konsole: enter image description here

Alle Ideen, wie diese Arbeit zu bekommen?

Code:

<!DOCTYPE html> 
    <body> 
    <script src="//d3js.org/d3.v3.min.js"></script> 
    <script> 

    var margin = {top: 20, right: 20, bottom: 20, left: 20}, 
     width = 960 - margin.left - margin.right, 
     height = 500 - margin.top - margin.bottom; 

    var svg = d3.select("body").append("svg") 
     .attr("width", width + margin.left + margin.right) 
     .attr("height", height + margin.top + margin.bottom) 
     .append("g") 
     .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); 

    d3.csv("data.csv", function(error, data){ 

      svg.selectAll("line") 
      .data(data) 
      .enter().append("svg:line") 
       .attr("x1", function(d, i) { return data[i].x }) 
       .attr("y1", function(d, i) { return data[i].y}) 
       .attr("x2", function(d, i) { return data[i+1].x}) 
       .attr("y2", function(d, i) { return data[i+1].y}) 
       .attr("fill", "none") 
       .attr("stroke", "red") 
       .attr("class", function(d,i){return "line" + i;}); 
    }); 

    </script> 

Here is a Plunker, die auch die Daten enthält.

Antwort

2

Ihre x2- und y2-Funktionen werden beim letzten Objekt im Array fehlerhaft sein, weil sie versuchen, auf die nächste Zeile zuzugreifen, die nicht existiert. Zum Beispiel ist Ihre array.length 258 und Sie sind in der Leitung 257; Die Funktionen x2 und y2 versuchen, auf die Zeile 258 zuzugreifen, die nicht existiert. Versuchen Sie:

svg.selectAll("line") 
     .data(data) 
     .enter().append("svg:line") 
      .attr("x1", function(d, i) { return data[i].x; }) 
      .attr("y1", function(d, i) { return data[i].y; }) 
      .attr("x2", function(d, i) { 

      // this the fix 
      // if there is a line at i+1 we will use it 
      // otherwise use the line at index 0 
      return data[i+1] ? data[i+1].x : data[ 0 ].x ; 

      }) 
      .attr("y2", function(d, i) { 

      // same as above but for y 
      return data[i+1] ? data[i+1].y : data[ 0 ].y ; 

      }) 
      .attr("fill", "none") 
      .attr("stroke", "red") 
      .attr("class", function(d,i){return "line" + i;}); 
+0

Oh, ich verstehe! Vielen Dank für die Erklärung und die Lösung für mich. Es ist sehr hilfreich. – sprucegoose

Verwandte Themen