Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using D3 to read csv returns html instead of csv data

Tags:

csv

d3.js

I have the following d3 code within script tags:

  d3.csv("data.csv", function(error, data) {
    data.forEach(function(d) {
      console.log(data[0]);

      d.date = parseDate(d.date);
      d.close = +d.close;
    });
    console.log("hello2")

    // Scale the range of the data
    x.domain(d3.extent(data, function(d) { return d.date; }));

    y.domain([0, d3.max(data, function(d) { return d.close; })]);

    svg.append("path") // Add the valueline path.
    .attr("class", "line")
    .attr("d", valueline(data));

    svg.append("g") // Add the X Axis
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

    svg.append("g") // Add the Y Axis
    .attr("class", "y axis")
    .call(yAxis);

  });

When I check the console in my browser, the output for the console.log was Object {<!DOCTYPE html>: "</head>"}. I'm expected the output to be {"date": "1-May-12", close: "58.13"}.

Why is the callback function using my html as the data parameter rather than my CSV data? Note that I am also running a simple node server so I can read the CSV.

like image 385
PC3SQ Avatar asked Oct 27 '25 17:10

PC3SQ


1 Answers

Let's start from the beginning ... I was trying to read the local csv data.csv from the same folder as my html containing the D3 script. That didn't work because there are built in browser security measures that prevent you from reading from your local machine. Without realizing that was what was causing an issue, I read other SO answers that led me to write my own node server to locally serve up my html and csv. That's when the bug that led me to create this SO question occurred.

The problem now was that when my D3 script was trying to read data.csv, it was reading the html file the D3 script was contained in; D3 was read in basic_chart.html instead of data.csv. That's why I was getting an object with key-value pairs describing an html file rather than a csv. I determined this had something to do with my server script but instead of rewriting the server script, I used the best answer from D3.js loading local data file from file:/// and served up my html and csv by typing python -m SimpleHTTPServer 8888 & on the command line while inside the target files' folder. It worked. Hope this helps someone else out. Thanks for your help @Cyril.

like image 93
PC3SQ Avatar answered Oct 29 '25 07:10

PC3SQ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!