Yousuf Farhan Yousuf Farhan - 5 months ago 8
Javascript Question

Why is nothing being displayed on my webpage?

The following is my code. Yet when I run it I get a blank page. Why is this the case ? Also how can I use data from hundreds of columns to make a simple interactive visual using d3 ? I would like to add that the following csv file "LoanStats3a.csv" is in the same folder.

<html>
<title>Loans</title>
<link href="../css/jquery-ui.css" rel="stylesheet" />
<script src="../Scripts/jquery-1.12.4"></script>
<script src="../Scripts/jquery-1.12.4.js"></script>
<script src="../Scripts/jquery-ui.js"></script>
<script src="http://d3js.org/d3.v3.js" charset="utf-8"></script>
<style>
#LoanStats3a{
color: blueviolet;
}
</style>
<body>
<script>
d3.csv("LoanStats3a", function (file1){
var bg = d3.select("body").append("svg")
.attr("width", 5000)
.attr("height", 5000);

bg.selectAll("rect")
.data(file1)
.enter()
.attr("width", function(d){return d.loan_amnt / 100;})
.attr("height", function(d) {return d.term;})
.attr("y", function (d,i) {return i *50;})
.attr("fill", function (d){"red","blue";});
}
</script>
</body>

Answer

This is because after binding the data to your empty selection, you have to append a rect element for each data.

Also, your attribute "fill" is incorrect.

bg.selectAll("rect")
    .data(file1)
    .enter()
    .append("rect") // <= You need to create a rect for each data
    .attr("width", function(d){return d.loan_amnt / 100;})
    .attr("height", function(d) {return d.term;})
    .attr("y", function (d,i) {return i *50;})
    .attr("fill", "blue");

If you want to change the color depending on the data, create a function and return something.

// For example
.attr("fill", function(d){return d.loan_amnt > 25000 ? "blue" : "red"});

Here's a JsFiddle with random data : DEMO