Google 图表 - 获取线性趋势线方程

5 html php charts google-visualization jsapi

我有一个像这样的图表(由谷歌图表绘制),该线是由谷歌生成的,带有线性趋势线选项

图像 在此输入图像描述

代码

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);
}
Run Code Online (Sandbox Code Playgroud)

如何知道这条直线的方程?

Whi*_*Hat 1

将趋势线添加到图例中将揭示方程式......

trendlines: {
  0: {
    visibleInLegend: true
  }
}
Run Code Online (Sandbox Code Playgroud)

如果需要,您可以从图例中删除该系列...

series: {
  0: {
    visibleInLegend: false
  }
},
Run Code Online (Sandbox Code Playgroud)

请参阅以下工作片段...

trendlines: {
  0: {
    visibleInLegend: true
  }
}
Run Code Online (Sandbox Code Playgroud)
series: {
  0: {
    visibleInLegend: false
  }
},
Run Code Online (Sandbox Code Playgroud)


编辑

将方程添加到图例后,您可以从用于绘制图例标记的元素
中获取值,但需要首先 等待事件, 才能知道图表已完成绘制<text>
'ready'

此外,您还需要一种方法来从其他标签中确定图例标记<text>元素
,例如
本例中的图表标题,标题和图例标记
都有一个text-anchor值为'start'

text-anchor可能会根据传说alignment而改变position

字体颜色 ( fill) 用于将标题与图例标记分开...

请参阅以下工作片段...

google.charts.load('current', {
  callback: drawChart,
  packages:['corechart']
});

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: {
      alignment: 'end',
      position: 'top'
    },
    series: {
      0: {
        visibleInLegend: false
      }
    },
    trendlines: {
      0: {
        visibleInLegend: true
      }
    }
  };

  var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
  chart.draw(data, options);
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
Run Code Online (Sandbox Code Playgroud)