在Google散点图上显示特定区域中的数据

时间:2013-10-31 20:52:58

标签: google-visualization

我有一个像这样的Google散点图:

<html>
  <head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Age', 'Weight'],
          [ 8,      12],
          [ 4,      5.5],
          [ 11,     14],
          [ 4,      5],
          [ 3,      3.5],
          [ 6.5,    7]
        ]);

        var options = {
          title: 'Age vs. Weight comparison',
          hAxis: {title: 'Age', minValue: 0, maxValue: 15},
          vAxis: {title: 'Weight', minValue: 0, maxValue: 15},
          legend: 'none'
        };

        var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="chart_div" style="width: 900px; height: 500px;"></div>
  </body>
</html>

我想点击一个圆圈,只显示选择圆圈半径x内的周期。任何的想法?? 谢谢!

1 个答案:

答案 0 :(得分:2)

您需要过滤DataTable以获取所选点的给定半径内的所有点。这里有一些代码可以帮到你:

google.visualization.events.addListener(chart, 'select', function () {
    var selection = chart.getSelection();
    if (selection.length > 0) {
        // get all data points within radius r of the selected point
        var r, x, y;
        r = <the radius to use>;
        x = data.getValue(selection[0].row, 0);
        y = data.getValue(selection[0].row, 1);

        var rows = [];
        for (var i = 0, count = data.getNumberOfRows(), dx, dy; i < count; i++) {
            dx = data.getValue(i, 0) - x;
            dy = data.getValue(i, 1) - y;
            if (Math.sqrt(dx * dx + dy * dy) <= r) {
                rows.push(i);
            }
        }
        // do something with filtered rows
    }
});

这是一个概念验证,展示了它的工作原理:http://jsfiddle.net/asgallant/tgshL/