2016-12-16 49 views
0

我用.csv文件中的數據製作了條形圖。我正在努力使條形圖的高度。我希望從特定列的數據值中獲取高度,在這種情況下,文件中的「無記錄停止」列。如何將我的條形圖高度作爲數據?

我已經試過了諸如:

.attr("height", function(d) {return d["NO OF RECORDS STOLEN"];} 

,但它不工作。

這是我的HTML:

<!DOCTYPE HTML> 
<html> 

<head> 
    <meta charset="utf-8"> 
    <title>Bar Chart | Crime File</title> 
    <script type="text/javascript" src="https://d3js.org/d3.v4.min.js"></script> 
</head> 

<body> 
    <script type="text/javascript"> 
     var dataset = "data_breaches.csv"; 

     var w = 960; 
     var h = 500; 
     var barPadding = 1; 
     var barWidth = w/dataset.length - barPadding; 

     // create canvas 
     var svg = d3.select("body") 
      .append("svg") 
      .attr("width", w) 
      .attr("height", h); 

     // create bar chart 
     svg.selectAll("rect") 
      .data(dataset) 
      .enter() 
      .append("rect") 
      .attr("x", function (d, i) { 
       return i * (barWidth + barPadding); 
      }) 
      .attr("y", 0) 
      .attr("width", barWidth) 
      .attr("height", 100) // WORKING ON THIS 
      .attr("fill", function (d) { 
       return "rgb(200, 50, 50)"; 
      }); 


     // get data 
     d3.csv(dataset, function (data) { 

      // convert type from string to integer 
      data.forEach(function typeConv(d) { 
       // type conversion from string to number 
       d["YEAR"] = +d["YEAR"]; // for names with spaces 
       d["DATA SENSITIVITY"] = +d["DATA SENSITIVITY"]; 
       d["NO OF RECORDS STOLEN"] = +d["NO OF RECORDS STOLEN"]; 
       return d; 
      }); 

      var arrayLength = data.length; 

      // fixed, should have been <, not <= bc n-1, not n 
      for (var i = 0; i < arrayLength; i++) { 
       var breachesData = data[i]; 
       console.log(breachesData); 
      } 
     }); 
    </script> 
</body> 

</html> 
+1

此代碼不會產生任何結果。依賴於'data'的繪圖部分必須**在**'d3.csv'裏面。此外,循環是無用的。 –

回答

0

正如你的問題的評論中提及,則需要追加數據加載後的矩形。此外,我審查了您的代碼,並刪除了不必要的部分以使清晰。請注意我添加的評論,如果您有任何問題,請告訴我們。祝你好運!

var dataset = "data_breaches.csv"; 

var w = 960; 
var h = 500; 
var barPadding = 1; 
var barWidth = w/dataset.length - barPadding; 

// create canvas 
var svg = d3.select("body") 
    .append("svg") 
    .attr("width", w) 
    .attr("height", h); 

// get data 
d3.csv(dataset, function (data) { 
    // You need to create a "scale" to convert from your data values to pixels in the screen 
    var heightBy = "NO OF RECORDS STOLEN" 
    var scale = d3.scaleLinear() 
     .domain([0, d3.max(d => d[heightBy])]) 
     .range([0, h]) 

    // create bar chart 
    svg.selectAll("rect") 
     .data(data) // "dataset" is the filepath, "data" is the loaded file content 
     .enter() 
     .append("rect") 
     .attr("x", (d, i) => i * (barWidth + barPadding)) 
     .attr("y", d => h - scale(d[heightBy])) // Remember that on SVG y=0 is at the bottom and the rect height grows down 
     .attr("width", barWidth) 
     .attr("height", d => scale(d[heightBy])) 
     .attr("fill", "rgb(200, 50, 50)"); 
}); 
相關問題