0

i have this code and i want to change the static data with data from csv

the csv is look like:

GPA,Total Distance,id
3.27,22.0,20032202
2,64.0,20038107
2.81,10.0,20051566
2.33,66.5,20060382

i want to add the GPA in y axis and total distance in the X axis

when i try to add code from d3 library it does not works

<html>
  <head>
  <script src="http://d3js.org/d3.v3.min.js"></script>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">

      google.charts.load('current', {
  packages: ['corechart', 'line']
});
google.charts.setOnLoadCallback(drawBasic);

function drawBasic() {

  var data = new google.visualization.DataTable();
  data.addColumn('number', 'X');
  data.addColumn('number', 'GPA');

  data.addRows([
    [0, 0],
    [1, 10],
    [2, 23],
    [3, 17],
    [4, 18],
  ]);

  var options = {
    hAxis: {
      title: 'Total Distance'
    },
    vAxis: {
      title: 'GPA'
    }
  };

  var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));

  chart.draw(data, options);
}

    </script>
  </head>
  <body>
    <div id="curve_chart" style="width: 900px; height: 500px"></div>
  </body>
</html>
Ms.J
  • 161
  • 1
  • 11

1 Answers1

1

Here is the best answer I can come up with to help you.

In your question, you have to tackle different topics in javascript

  • get content of a local file in javascript
  • parse this content as a csv file (and make it a multidimensional array)
  • prepare the values to put in the chart

First, add the following two libraries : jQuery for the simplified ajax calls to the file and jquery-csv for an also simplified way to parse the content.

<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>

Then, you have to re-route the charts callback : you have to point to a function that get asynchronously the file content (getFileContent in the example below).

Only in case of success, you can format the csv data into array.

And only then, you can serve the data to the chart by passing your formatted and sorted array to your drawbasic method.

Finally, you end up with that script

<script type="text/javascript">
    google.charts.load('current', {
        packages: ['corechart', 'line']
    });
    google.charts.setOnLoadCallback(getFileContent);

    function getFileContent() {
        var filePath = 'file:///path/to/file.csv';

        // 1. Get local file content asynchronously
        $.get(filePath, {}, function (data) {
            console.log(arguments);
            var lines = $.csv.toArrays(data); // 2. Parse the csv as a multidimensional array
            var header = lines.shift(); // 3. Remove the header of the file
            // 4. Sort the lines by the second column
            lines.sort(function (a, b) {
                if (a[1] === b[1]) {
                    return 0;
                }
                else {
                    return (a[1] < b[1]) ? -1 : 1;
                }
            });

            // 5. Pass your lines to the draw method
            drawBasic(lines);
        }, 'text')
                .fail(function () {
                    console.log(arguments);
                })
        ;
    }

    function drawBasic(lines) {
        var data = new google.visualization.DataTable();
        data.addColumn('number', 'X');
        data.addColumn('number', 'GPA');

        for (i = 0; i < lines.length; i++) {
            // 6. Don't forget to parse as float the numbers in the array, they are strings at this point
            // You'll get a 'Type mismatch. Value 3,27 does not match type number' error if you don't
            var xValue = parseFloat(lines[i][1]);
            var yValue = parseFloat(lines[i][0]);
            data.addRow([xValue, yValue]);
        }

        var options = {
            hAxis: {
                title: 'Total Distance'
            },
            vAxis: {
                title: 'GPA'
            }
        };

        var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));

        chart.draw(data, options);
    }
</script>

Don't forget to change the filepath in getFileContent, preceded by file://

I give credit to the answers in SO that helped me create this answer:

Side note

In different conditions, it's much more common if you get csv (or, better with Javascript, JSON) via an HTTP call when working with Javascript to display data. Local file reading may be reserved for server-side processing, that make this content available through HTTP.

Community
  • 1
  • 1
Lex Lustor
  • 1,525
  • 2
  • 22
  • 27