I am just starting with D3 and having trouble binding data from an external file. Note that I am serving this html file locally and opening from the server, not the file (see screenshots below).
When I try to bind to a var defined within the html file ("d2"), everything works fine. However when I try to bind to the data read from the csv file ("d"), even though I can see that data in the developer tools, the DOM elements do not appear as expected.
Why does the first code work as expected, but not the second?
I recognize this is probably something obvious, but have not been able to find - or at least understand - the answer in the docs or in other questions.
I have read this question, which may be the same, but the suggested answer has not been accepted. I played around with my csv format as the one respondent suggests, but it did not solve the issue. This question does not seem to apply, as I've taken the advice to avoid the asynchronous loading issue.
Thank you in advance for any help!
Here's the code snippet that works as expected (full html file included toward end of this post):
var d2 = [1,2,3,4,5];
d3.csv("./Fake2.csv", function(d)
{
console.log(d2);
d3.select("body").selectAll("p")
.data(d2)
.enter()
.append("p")
.text("New paragraph");
});
Results in this page (screen shot with Chrome developer tools on left side):
Note that there are seven entries in the console because the csv file has seven data rows (see file below).
However, when I change the d3 code to bind to data read from the csv file ("d"), there are no paragraph elements added to the DOM and there is no text on the webpage. In the console, however, the data are correctly presented.
Adjusted code (note "d2" changed to "d" within d3.csv block):
var d2 = [1,2,3,4,5];
d3.csv("./Fake2.csv", function(d)
{
console.log(d);
d3.select("body").selectAll("p")
.data(d)
.enter()
.append("p")
.text("New paragraph");
});
Resulting in this "blank webpage" output:
Here's the entire HTML file:
<!-- Attempt1.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>School Finance Viz</title>
<link rel="stylesheet" type="text/css" href="styles.css"/>
<script type="text/javascript" src="d3.js"></script>
</head>
<body>
</body>
<script type="text/javascript">
var d2 = [1,2,3,4,5];
d3.csv("./Fake2.csv", function(d)
{
console.log(d2);
d3.select("body").selectAll("p")
.data(d2)
.enter()
.append("p")
.text("New paragraph");
});
</script>
Here's the entire csv file:
Category
1000
500
100
400
1600
300
100
Note that the solution of this (accepted below) is the same as the solution to this question. The underlying problem is, in fact, the same, but the symptoms of the problem are different, making this a different question for the purposes of those new to D3.