Google charts - Get the equation of Linear trendlines

Viewed 1961

I have a chart like this (drawn by google charts) the line is generated by google with option of Linear trendlines

image enter image description here

code

google.charts.setOnLoadCallback(drawChart);
function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['Diameter', 'Age'],
    [8, 37], [4, 19.5], [11, 52], [4, 22], [3, 16.5], [6.5, 32.8], [14, 72]]);

  var options = {
    title: 'Age of sugar maples vs. trunk diameter, in inches',
    hAxis: {title: 'Diameter'},
    vAxis: {title: 'Age'},
    legend: 'none',
    trendlines: { 0: {} }    // Draw a trendline for data series 0.
  };

  var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
  chart.draw(data, options);
}

how to know the equation of this line?

2 Answers

This works for me:

var container = document.getElementById('chart_div');
var chart = new google.visualization.ScatterChart(container);

google.visualization.events.addListener(chart, 'ready', function () {
  console.log(chart.Zl().jp[1].text);
});

chart.draw(data, options);

chart.Zl().jp looks like this:

 [
  {
    "id": "",
    "text": "Age",
    "brush": "{\"fill\":\"#3366cc\",\"fillOpacity\":1,\"stroke\":\"none\",\"strokeWidth\":1,\"strokeOpacity\":1,\"strokeDashStyle\":\"solid\",\"rx\":null,\"ry\":null,\"gradient\":null,\"pattern\":null,\"shadow\":null}",
    "index": 0,
    "ja": false
  },
  {
    "id": "_trendline",
    "text": "y = 4.885 * x + 0.73",
    "brush": "{\"fill\":\"#3366cc\",\"fillOpacity\":0.5,\"stroke\":\"none\",\"strokeWidth\":1,\"strokeOpacity\":1,\"strokeDashStyle\":\"solid\",\"rx\":null,\"ry\":null,\"gradient\":null,\"pattern\":null,\"shadow\":null}",
    "index": 1,
    "ja": true
  }
]

so for each series there will be two objects, one for series and second for trendline, so if for example you have two trendlines you can get the second equation with chart.Zl().jp[3].text

Related