Dave
Dave

Reputation: 103

Multiple data points per date in Google Charts

I am using a standard php array that pulls data from a database in reverse order to create a Google Chart. Something like this...

$graph_data = array(array('Date', 'Amount'));
foreach (array_reverse($transactions) as $transaction) 
{ 
    array_push($graph_data, array(date("d M", strtotime(substr($transaction->createdOn, 0, 10))), $transaction->balanceAfter + 0));
    }

Works fine.

This process creates a new data point on the chart for each row of the array. The problem I have is when there are multiple events ($transaction) on a date. Each event is plotted as a new chart point, whereas I would like to graph the last data point for each date. (constant time series)

What is the best way to go about this?

Is there a simple google chart setting to use the last data point per date? I have searched but found nothing on this.

Thanks

Upvotes: 3

Views: 1257

Answers (1)

WhiteHat
WhiteHat

Reputation: 61212

we can use the group() method,
with a custom aggregation function,
to only display the last point for a given date.

var dataLast = google.visualization.data.group(
  data,  // data table
  [0],   // group by column
  [{     // aggregated column
    column: 1,
    type: 'number',
    label: data.getColumnLabel(1),
    // aggregation function
    aggregation: function (values) {
      // return the last value for the group
      return values[values.length - 1];
    }
  }]
);

the aggregation property above,
should be a function that accepts a single argument,
that is an array of the values for each group.

in this case, we just return the last value in the array.

the group method returns a data table,
which we can use to draw the chart.

see following working snippet...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = google.visualization.arrayToDataTable([
    ['Date', 'Amount'],
    ['09 Jan', 13],
    ['29 Jan', 11],
    ['29 Jan', 9],
    ['29 Jan', 4],
    ['29 Jan', -3],
    ['29 Jan', 0],
    ['29 Jan', -3],
    ['30 Jan', -5],
    ['30 Jan', 0],
    ['30 Jan', -1],
    ['30 Jan', -2],
    ['30 Jan', -3],
    ['30 Jan', -4],
    ['30 Jan', -5]
  ]);

  var dataLast = google.visualization.data.group(
    data,  // data table
    [0],   // group by column
    [{     // aggregated column
      column: 1,
      type: 'number',
      label: data.getColumnLabel(1),
      // aggregation function
      aggregation: function (values) {
        // return the last value for the group
        return values[values.length - 1];
      }
    }]
  );

  var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
  chart.draw(dataLast);  // use grouped data to draw the chart
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Upvotes: 1

Related Questions