Reputation: 200
I have data for the graph that contain 4 columns (X axis values with type datetime and 3 Y axis values with type number). And I'm building a chart with 3 lines (nothing unusual):
var chartDataTable = new google.visualization.DataTable();
// get data to chartDataTableRows variable by ajax
chartDataTable.addRows(chartDataTableRows);
var _chartContainer = $('<div id="_chart"</div>').appendTo($('#_tempChart'));
var chart = new google.visualization.LineChart(_chartContainer[0]);
chart.draw(chartDataTable, defaultChartOptions());
Now I need to add to the chart one more line that will display the sum of the indicators of the existing three lines. Are there any such tools in GoogleCharts?
Upvotes: 4
Views: 469
Reputation: 61222
you can use a DataView
with a calculated column for the total
1) create a DataView
over the DataTable
var chartDataView = new google.visualization.DataView(chartDataTable);
2) use the setColumns
method to provide the columns for the DataView
provide the column index for the existing columns,
and a calculated column for the total...
chartDataView.setColumns([0, 1, 2, 3, {
type: 'number',
label: 'total',
calc: function (dt, row) {
var rowTotal = 0;
for (var col = 1; col < chartDataTable.getNumberOfColumns(); col++) {
rowTotal += chartDataTable.getValue(row, col);
}
return rowTotal;
}
}]);
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var chartDataTable = new google.visualization.DataTable();
chartDataTable.addColumn('date', 'x');
chartDataTable.addColumn('number', 'y0');
chartDataTable.addColumn('number', 'y1');
chartDataTable.addColumn('number', 'y2');
chartDataTable.addRows([
[new Date(2018, 2, 28), 5, 2, 8],
[new Date(2018, 2, 29), 7, 3, 6],
[new Date(2018, 2, 30), 3, 0, 9],
[new Date(2018, 2, 31), 1, 5, 9],
[new Date(2018, 3, 1), 3, 6, 7],
[new Date(2018, 3, 2), 4, 7, 8],
[new Date(2018, 3, 3), 3, 1, 8],
[new Date(2018, 3, 4), 4, 2, 6],
[new Date(2018, 3, 5), 2, 3, 5]
]);
var chartDataView = new google.visualization.DataView(chartDataTable);
chartDataView.setColumns([0, 1, 2, 3, {
type: 'number',
label: 'total',
calc: function (dt, row) {
var rowTotal = 0;
for (var col = 1; col < chartDataTable.getNumberOfColumns(); col++) {
rowTotal += chartDataTable.getValue(row, col);
}
return rowTotal;
}
}]);
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(chartDataView);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
Upvotes: 2