So I'm trying to create a graph using google charts, but I can't find any mathmatical functions to use. What I've done is just calculate by hand what the results of the equation are and put them into the dataset (in this case I've calculated y=x^2). Although this works fine, I'm planning to create more graphs and I can't really be bothered to calculate all by hand. Is it possible to use a mathmatical equation? If so, could you please provide the code for that? Thanks
there are probably several ways to accomplish, here are a couple...
1) use a data view with a calculated column
after you create the data table, create a data view from the table...
var view = new google.visualization.DataView(data);
then you can use the setColumns
method.
using this method, you pass an array of column definitions.
you can either pass the column index as a number,
or a calculated column as an object.
here, the first column in the data table is included,
along with a calculated column...
view.setColumns([0, {
calc: function (dt, row) {
var x = dt.getValue(row, 0);
return Math.pow(x, 2);
},
label: 'y',
type: 'number'
}]);
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = new google.visualization.DataTable();
data.addColumn('number','x');
data.addRows([
[0],
[1],
[2],
[3],
[4],
[5],
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, {
calc: function (dt, row) {
var x = dt.getValue(row, 0);
return Math.pow(x, 2);
},
label: 'y',
type: 'number'
}]);
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(view);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
2) another option would be to perform the calculation, as the data table is loaded...
for (var i = 0; i < 10; i++) {
data.addRow([i, Math.pow(i, 2)]);
}
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = new google.visualization.DataTable();
data.addColumn('number','x');
data.addColumn('number','y');
for (var i = 0; i < 10; i++) {
data.addRow([i, Math.pow(i, 2)]);
}
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>