Reputation: 1789
I wish to replace this portion of my script (from a dashingd3js tutorials) with a reference to a CSV file with the same data.
var lineData = [ { "x": 1, "y": 5}, { "x": 20, "y": 20},
{ "x": 40, "y": 10}, { "x": 60, "y": 40},
{ "x": 80, "y": 5}, { "x": 100, "y": 60}];
The csv is located in the same directory and named 'dataFile.csv'
dataFile.csv:
x,y
1,5
20,20
40,10
60,40
80,5
100,60
Edit: Trying to incorporate feedback from Lars and d3noob, this is what I tried:
//The data for our line
d3.csv("testData.csv", function(error, lineData){
//This is the accessor function we talked about above
var lineFunction = d3.svg.line()
.x(function(d) { return d.x; })
.y(function(d) { return d.y; })
.interpolate("linear");
//The SVG Container
var svgContainer = d3.select("body").append("svg")
.attr("width", 200)
.attr("height", 200);
//The line SVG Path we draw
var lineGraph = svgContainer.append("path")
.attr("d", lineFunction(lineData))
.attr("stroke", "blue")
.attr("stroke-width", 2)
.attr("fill", "none");
}
Here is another version of the code which I am editing as I do more research. It currently does not work.
//The data for our line
d3.csv("testData.csv", function(d){
return{
lineData.x: d.x,
lineData.y: d.y };
}, function(error, rows) {
console.log(rows);
});
//This is the accessor function we talked about above
var lineFunction = d3.svg.line()
.x(function(d) { return d.x; })
.y(function(d) { return d.y; })
.interpolate("linear");
//The SVG Container
var svgContainer = d3.select("body").append("svg")
.attr("width", 200)
.attr("height", 200);
//The line SVG Path we draw
var lineGraph = svgContainer.append("path")
.attr("d", lineFunction(lineData))
.attr("stroke", "blue")
.attr("stroke-width", 2)
.attr("fill", "none");
}
Upvotes: 0
Views: 260
Reputation: 1344
Your drawing code needs to stay inside csv callback:
d3.csv("testData.csv", function(data){
// this converts data to number
data.forEach(function(d) {
d.x = +d.x;
d.y = +d.y;
});
// rest of drawing code
...
});
See another example here:
http://vida.io/documents/QZZTrhk7SmfChczYp
It's easier to debug if you can post link to working code.
Upvotes: 2
Reputation: 109232
You need to load the file through an asynchronous request with d3.csv
. Example code:
d3.csv("dataFile.csv", function(error, data) {
// do something exciting with data
}
Upvotes: 0