Search code examples
javascriptchartsgoogle-visualizationstackedtrendline

Google Charts - Trendline for Stacked Column Chart


My problem is about a stacked column bar chart with Google Charts API.

I am trying to get a global trendline out of it.

<script type="text/javascript">
 google.charts.load("current", {"packages":["corechart"]});
 google.charts.setOnLoadCallback(drawVisualization);
 function drawVisualization() {
 var data = google.visualization.arrayToDataTable([['Month', 'OK', 'KO', 'Estimation'],[ '2016/08', 1990, 49, null ],[ '2016/09', 6892, 97, null ],[ '2016/10', 6018, 0, null ],[ '2016/11', 7329, 146, null ],[ '2016/12', 3059, 97, 1827 ]]);
 var options = {
  isStacked: true,
  seriesType: "bars",
  legend: "none",
  hAxis:{ textPosition: "none" },
  vAxis: { viewWindow: { min: 0, max: 8000 } },
  trendlines: { 0: {} }
 };
 var chart = new google.visualization.ComboChart(document.getElementById("bar"));
 chart.draw(data, options);
 }
 </script>

When I add trendlines: { 0: {} }, I get no results.

I haven't found anything on the reference guide. Maybe it is not implemented, or I do it wrong ?


Solution

  • although not mentioned in the documentation, trendlines are only supported on a Continuous x-axis

    this means the values for the first column should be a date, number, etc...

    string values result in a Discrete axis

    see discrete vs continuous...

    see following working snippet...

    the first column is converted to an actual date using a DataView, which enables trendlines...

    google.charts.load('current', {
      callback: function () {
        var data = google.visualization.arrayToDataTable([
          ['Month', 'OK', 'KO', 'Estimation'],
          ['2016/08', 1990, 49, null],
          ['2016/09', 6892, 97, null],
          ['2016/10', 6018, 0, null],
          ['2016/11', 7329, 146, null],
          ['2016/12', 3059, 97, 1827]
        ]);
    
        var view = new google.visualization.DataView(data);
        view.setColumns([{
          calc: function (dt, row) {
            var dateParts = dt.getValue(row, 0).split('/');
            return new Date(parseInt(dateParts[0]), parseInt(dateParts[1]) - 1, 1);
          },
          type: 'date',
          label: data.getColumnLabel(0)
        }, 1, 2, 3]);
    
        var options = {
          isStacked: true,
          seriesType: 'bars',
          legend: 'none',
          hAxis: {
            textPosition: 'none'
          },
          vAxis: {
            viewWindow: {
              min: 0,
              max: 8000
            }
          },
          trendlines: {
            0: {}
          }
        };
    
        var chart = new google.visualization.ComboChart(document.getElementById('bar'));
        chart.draw(view, options);
      },
      packages:['corechart']
    });
    <script src="https://www.gstatic.com/charts/loader.js"></script>
    <div id="bar"></div>