ratsstack
ratsstack

Reputation: 1021

Google Annotation Chart load from CSV

I am trying to create a Google Annotation chart by loading some data from a CSV file using the example found here:

https://developers.google.com/chart/interactive/docs/gallery/annotationchart

I've tried to modify the code (using my limited JS knowledge) to load from a CSV file but I'm getting no graph.

My code so far:

<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type='text/javascript'>
google.charts.load('current', {'packages':['annotationchart']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() 
{
$.get('test.csv', function(csvString) 
{
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
arrayData = arrayData.map(function (row) 
{
return 
[new Date(row[0]),row[1]];
});


var data = google.visualization.arrayToDataTable(arrayData);
var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'));

var options = {
displayAnnotations: true
};

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

<body>
<div id='chart_div' style='width: 900px; height: 500px;'></div>
</body>
</html>

CSV File

Date,Value1
2014-01-01,1233
2014- 01-02,1334
2014-01-03,1488
2014-01-04,1888
2014-01-05,2011
2014-01-06,1900
2014-01-07,1768
2014-01-08,2345

Upvotes: 3

Views: 509

Answers (2)

WhiteHat
WhiteHat

Reputation: 61222

first, add jquery and jquery csv to your page.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>

then replace the code as follows.
see comments for explanations...

// load google charts
google.charts.load('current', {
  packages: ['annotationchart']
}).then(function () {
  // declare data variable
  var arrayData;

  // get csv data
  $.get('test.csv', function(csvString) {
    // get csv data success, convert to an array, draw chart
    arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
    drawChart(arrayData);
  }).fail(function () {
    // get csv data failed, draw chart with hard-coded data, for example purposes
    arrayData = [
      ['Date','Value1'],
      ['2014-01-01',1233],
      ['2014-01-02',1334],
      ['2014-01-03',1488],
      ['2014-01-04',1888],
      ['2014-01-05',2011],
      ['2014-01-06',1900],
      ['2014-01-07',1768],
      ['2014-01-08',2345],
    ];
    drawChart(arrayData);
  });
});

// draw chart
function drawChart(arrayData) {
  // convert string in first column to a date
  arrayData = arrayData.map(function (row) {
    return [new Date(row[0]),row[1]];
  });

  // create google data table, chart, and options
  var data = google.visualization.arrayToDataTable(arrayData);
  var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'));
  var options = {
    displayAnnotations: true
  };

  // draw chart
  chart.draw(data, options);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

note: you can remove the fail callback, it is for example purposes here on stack overflow...

Upvotes: 3

Paresh Barad
Paresh Barad

Reputation: 1609

You need to follow 3 step for this task

  1. Fire ajax request and take csv data
  2. Convert csv data into array
  3. Pass csv array in google graph

Please take refrence from following example:

<html>
<head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type='text/javascript'>

        //Step 1: Get string from csv
        $(document).ready(function () {
            $.ajax({
                type: "GET",
                url: "test.csv",
                dataType: "text",
                success: function (data) {
                    //Step 2: Convert "," seprated string into array
                    let arrData = csvToArray(data);
                    //Step 3: call chart with array data
                    callChart(arrData);
                }
            });
        });

        //convert csv string into array function
        function csvToArray(allText) {
            var allTextLines = allText.split(/\r\n|\n/);
            var headers = allTextLines[0].split(',');
            var lines = [];

            for (var i = 1;i < allTextLines.length;i++) {
                var data = allTextLines[i].split(',');
                if (data.length == headers.length) {

                    var tarr = [];
                    for (var j = 0;j < headers.length;j++) {
                        tarr.push(headers[j] + ":" + data[j]);
                    }
                    lines.push(tarr);
                }
            }
            return lines;
        }

        function callChart(arrData) {
            google.charts.load('current', { 'packages': ['annotationchart'] });
            google.charts.setOnLoadCallback(function () { drawChart(arrData); });
        }

        function drawChart(arrData) {
            var data = new google.visualization.DataTable();
            //Step 4: add csv your column
            data.addColumn('date', 'Date');
            data.addColumn('number', 'Kepler-22b mission');
            //Step 5: pass your csv data as array
            data.addRows(arrData);
            var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'));
            var options = {
                displayAnnotations: true
            };
            chart.draw(data, options);
        }
    </script>
</head>
<body>
    <div id='chart_div' style='width: 900px; height: 500px;'></div>
</body>
</html>

Upvotes: 0

Related Questions