Search code examples
google-visualizationtrendline

Google-chart trendline not showing


Google-chart trend-line not showing. Tried to put the code in vAxis, hAxis and only in options but no luck. I know that the first column must be a number or date and so on and my first column is a date.

 <script type="text/javascript">
  data.sort([{column: 0}]);
  google.charts.load('current', {'packages':['corechart']});
  google.charts.setOnLoadCallback(drawChart);

  function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['Date', 'Sum'],
       <?php while($row = mysqli_fetch_assoc($result)) { ?>

      [<?php echo $row['date'] ?>,  <?php echo $row['col2'] ?> ],

    <?php } ?>
    ]);

    var options = {
         legend: { position: 'bottom' },
        title: 'Sum per day',
         hAxis : { textStyle : { fontSize: 10 } },
    vAxis: { viewWindowMode: 'explicit', viewWindow: { min: 0 } },
    trendlines: { 0: {} }
    };

    var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
    chart.draw(data, options);
  }
</script>

enter image description here


Solution

  • when loading the data, the first column needs to be converted from a string to a date.
    place the value from php in quotes and inside a date constructor.

    e.g.

    [new Date('<?php echo $row['date'] ?>'),  <?php echo $row['col2'] ?> ],
    

    if you still have problems with the squiggly line,
    sort the data before drawing...

    data.sort([{column: 0}]);
    var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
    chart.draw(data, options);