4

I have a CSV file with datetime timestamps (in milliseconds from 1970) as X axis separed tis a comma ',' and an associated Temperature value as Y axis.

ie :

1485097200000,22.5
1485098100000,23.8
1485099000000,24.2
etc ...

From that kind of CSV file i would like to generate a google graph code like this :

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


google.load('visualization', '1', {'packages':['annotatedtimeline']});
google.setOnLoadCallback(drawChart);
function drawChart() {

  var data = new google.visualization.DataTable();
  data.addColumn('datetime', 'Date');
  data.addColumn('number', 'Temperatures');

  data.addRows([
    [new Date(1485097200000), 22.5],
    [new Date(1485098100000), 23.8],
    [new Date(1485099000000), 24.2]
  ]);


  var options = {
    title: 'Temperature measured every 15 minutes',
    width: 900,
    height: 500,
    hAxis: {

      gridlines: {count: 15}
    },
    vAxis: {
      gridlines: {color: 'none'},
      minValue: 0
    }
  };

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

  chart.draw(data, options);

  var button = document.getElementById('change');



  button.onclick = function () {

    // If the format option matches, change it to the new option,
    // if not, reset it to the original format.
    options.hAxis.format === 'M/d/yy' ?
      options.hAxis.format = 'MMM dd, yyyy' :
    options.hAxis.format = 'M/d/yy';

    chart.draw(data, options);
  };
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<button id="change">Click to change the format</button>
<div id="chart_div"></div>

Would you please tell if it is possible and how i could do it so , i'm newbie.

Regards,

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
Laurent Coulon
  • 109
  • 1
  • 11
  • What the problem to use the code in the jsfiddle? With milliseconds? I'm not sure what miss? – Mosh Feu Jan 22 '17 at 13:07
  • There is no issue with jsfiffle.net, i only want to know how i could parse datas from a CSV file in order to populate lines into data.addRows([ ... ]); and generate the Google Graph – Laurent Coulon Jan 22 '17 at 15:26
  • check [this question and answer](http://stackoverflow.com/q/38517946/5090771) for using jquery to get the csv and load google charts... – WhiteHat Jan 23 '17 at 00:32

1 Answers1

2

Here is an example for how to get the get the data from a CSV file (in this case come from a string but the principal is the same.

The CSV file should look like this:

1486727700000,5\n1486728600000,7\n1486729200000,3\n1486729800000,1\n1486730400000,3\n1486731000000,4\n1486731600000,3\n1486732200000,4\n1486732800000,4

Also you need to extract the data from the file so here is the function.

function getData(csv) {
  var output = [];
  csv.split(/\n/).forEach(function(row) {
    var cells = row.split(','),
        date = new Date(parseInt(cells[0])),
        value = parseFloat(cells[1]);

    output.push([date, value]);
  });

  return output;
}

And live demo here:

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

// google.load('visualization', '1', {'packages':['annotatedtimeline']});
// google.setOnLoadCallback(drawChart);

function drawChart() {
  var data = new google.visualization.DataTable();
  data.addColumn('datetime', 'Date');
  data.addColumn('number', 'Temperatures');

  //   data.addRows([
  //     [new Date(2017, 1, 10, 13, 55), 5],  [new Date(2017, 1, 10, 14, 10), 7],  [new Date(2017,1, 10,14,20), 3],
  //     [new Date(2017, 1, 10, 14, 30), 1],  [new Date(2017, 1, 10, 14,40), 3],  [new Date(2017, 1, 10, 14,50), 4],
  //     [new Date(2017, 1, 10,15,00), 3],  [new Date(2017, 1, 10,15,10), 4],  [new Date(2017, 1, 10,15,20), 2]
  //   ]);

  data.addRows(getData(csvFile));

  var options = {
    title: 'Temperature measured every 15 minutes',
    width: 900,
    height: 500,
    hAxis: {

      gridlines: {count: 15}
    },
    vAxis: {
      gridlines: {color: 'none'},
      minValue: 0
    }
  };

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

  chart.draw(data, options);

  var button = document.getElementById('change');

  button.onclick = function () {

    // If the format option matches, change it to the new option,
    // if not, reset it to the original format.
    options.hAxis.format === 'M/d/yy' ? options.hAxis.format = 'MMM dd, yyyy' : options.hAxis.format = 'M/d/yy';

    chart.draw(data, options);
  };
}

var csvFile = '1486727700000,5\n1486728600000,7\n1486729200000,3\n1486729800000,1\n1486730400000,3\n1486731000000,4\n1486731600000,3\n1486732200000,4\n1486732800000,4';

function getData(csv) {
  var output = [];
  csv.split(/\n/).forEach(function(row) {
    var cells = row.split(','),
        date = new Date(parseInt(cells[0])),
        value = parseFloat(cells[1]);

    output.push([date, value]);
  });

  return output;
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

<button id="change">Click to change the format</button>
<div id="chart_div"></div>

http://output.jsbin.com/coxemay

Update

How to get the CSV from file using ajax

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

function drawChart(csvData) {
  var data = new google.visualization.DataTable();
  data.addColumn('datetime', 'Date');
  data.addColumn('number', 'Temperatures');

  getData(function(csvData) {
    data.addRows(csvData);

    var options = {
      title: 'Temperature measured every 15 minutes',
      width: 900,
      height: 500,
      hAxis: {

        gridlines: {count: 15}
      },
      vAxis: {
        gridlines: {color: 'none'},
        minValue: 0
      }
    };

    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(data, options);
  });


  var button = document.getElementById('change');

  button.onclick = function () {

    // If the format option matches, change it to the new option,
    // if not, reset it to the original format.
    options.hAxis.format === 'M/d/yy' ? options.hAxis.format = 'MMM dd, yyyy' : options.hAxis.format = 'M/d/yy';

    chart.draw(data, options);
  };
}

function getData(callback) {
  $.get('https://gist.githubusercontent.com/moshfeu/e3fd00cb57ae5b5cffbda44422dff112/raw/bcadcdfb5a532cc5711949a60cce639b2da235e6/csv-file', function(csv) {
    var output = [];
    csv.split(/\n/).forEach(function(row) {
      var cells = row.split(','),
          date = new Date(parseInt(cells[0])),
          value = parseFloat(cells[1]);

      output.push([date, value]);
    });

    callback(output);
  });
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

<button id="change">Click to change the format</button>
<div id="chart_div"></div>

http://jsbin.com/coxemay/3/edit?html,js,console

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
  • Thank you very much Mosh Feu. – Laurent Coulon Jan 23 '17 at 05:41
  • If the CSV file has a third data on each line, is it possible to draw that one on the graph with a second Y axis ? I also would like to let the user define by himself the time line range in order to draw a specific part of graph according to a specified time window, user would enter into 2 textboxes first and last date for desired graph . Is these enhancements possible ? – Laurent Coulon Jan 23 '17 at 05:47
  • In your example, you set the csvfile as a variable. If i have a separe csv file , ie : data.csv that holds the datas what should i modify in the code to let the function load that file first ? Should i add something like : url: 'data.csv', type: 'get', success: – Laurent Coulon Jan 23 '17 at 08:11
  • `If the CSV file has a third data on each line, is it possible to draw that one on the graph with a second Y axis` I'm not sure I understand. `Is these enhancements possible` Yes. `Should i add something like` As much as I know google doesn't support ajax built-in. Get the data using ajax the way you prefer, then call `drawChart` with the response data. – Mosh Feu Jan 23 '17 at 12:41
  • Can you please show me how I could load the csv file from an URL and process it afterwards ? – Laurent Coulon Jan 23 '17 at 12:46
  • It works from the CSV file. Do you know why i can't add to that graph : google.load('visualization', '1', {'packages':['annotatedtimeline']}); This feature would be very usefull for me but looks to be incompatible with google.charts.load('current', {'packages': ['corechart']}); What did i again wrong ? – Laurent Coulon Jan 23 '17 at 23:25
  • According the docs, you can load the package using this code: `google.charts.load('current', {'packages':['annotatedtimeline']});`. So my guess is that if you want to load multiple packages just add it to the packages array. Like this: `google.charts.load('current', {'pa3ckages':['corechart', 'annotatedtimeline']});` – Mosh Feu Jan 24 '17 at 06:19
  • google.charts.load('current', {'packages':['corechart', 'annotatedtimeline']}); does not display the annotated time line, only the graph is displayed. please see result here : http://output.jsbin.com/vixoqiqasa – Laurent Coulon Jan 24 '17 at 07:42
  • As much as I understand the `annotatedtimeline` is completely different thing. To use this you need to call `new google.visualization.AnnotatedTimeLine` instead of `new google.visualization.LineChart` and some more changes. Keep attention that you can't use the `lineChart` futures when you using it. http://jsbin.com/viruja/edit?html,js,output Also, you can read the [docs](https://developers.google.com/chart/interactive/docs/gallery/annotatedtimeline) – Mosh Feu Jan 24 '17 at 10:38
  • May i ask another thing please, i need to display the dates in X axis issued from CSV file in 24h format, like this : 'dd/MM/yyyy HH:mm' . I can't get it working, dates stay in AM PM – Laurent Coulon Jan 24 '17 at 22:19
  • I think that you can't but I'm not sure. You can ask this as different question here on StackOverflow. I'm hoping someone will know the answer for sure. – Mosh Feu Jan 25 '17 at 09:23
  • @LaurentCoulon If my answer works for your original question please accept it so it could help to other people. Thanks. – Mosh Feu Jan 25 '17 at 14:03
  • @LaurentCoulon My pleasure :) Do you know [how to accept an answer](http://stackoverflow.com/help/someone-answers)? – Mosh Feu Jan 25 '17 at 14:24
  • No, not yet sorry – Laurent Coulon Jan 25 '17 at 14:25