6

我有一个例子:

// Load the Visualization API and the piechart package.
        google.load('visualization', '1.0', {'packages':['corechart']});

        // Set a callback to run when the Google Visualization API is loaded.
        google.setOnLoadCallback(drawChart1);

        // Callback that creates and populates a data table,
        // instantiates the pie chart, passes in the data and
        // draws it.
        function drawChart1() {
            var data = new google.visualization.DataTable(
            {
                cols: [
                    {id: 'A', label: 'A', type: 'number'},
                    {id: 'B', label: 'B', type: 'number'},
                    {id: 'C', label: 'C', type:'tooltip', p:{role:'tooltip'}}
                ],
                rows: [
                    {c:[{v: 2}, {v: 3}, {v:'Allen'}]},
                    {c:[{v: 4}, {v: 2}, {v:'Tom'}]},
                    {c:[{v: 1}, {v: 3}, {v:'Sim'}]}

                ]
            })

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

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

http://jsfiddle.net/eAWcC/1/

当我悬停一次数据时,工具提示将看到我为该数据添加的标签。那很好。

但我想看到所有的值都是不同的颜色并放在图例中。

例子

怎么做?

4

1 回答 1

9

散点图数据表中的列是图例中显示的列,并且颜色不同。为了分别显示它们,您需要重新排列数据,以便每个人都有自己的列。

例如,将您的数据表变量替换为:

            var data = google.visualization.arrayToDataTable([
              ['x', 'Allen', 'Tom', 'Sim'],
              [1, null, null, 3],
              [2, 3, null, null],
              [4, null, 2, null],
            ]);

这样做会给你想要的输出(我相信,在这里检查)。

但是,这种方法的问题是您最终在每个系列中都有很多“空”值(因为您只有单点)。为了简化此过程,您可以编写一个循环来遍历您的数据并为新表设置适当的格式。基本代码是:

  1. 将 X 值的列添加到新表中
  2. 对于第 2 列(工具提示)中的每一行,在新表中创建一个新列
  3. 对于第 1 列(Y 值)中的每一行,沿对角线向下/向右填充

这看起来像这样:

          var newTable = new google.visualization.DataTable();

          newTable.addColumn('number', 'Age');
          for (var i = 0; i < data.getNumberOfRows(); ++i) {
            newTable.addColumn('string', data.getValue(i, 2));
            newTable.addRow();
          }

          for (var j = 0; j < data.getNumberOfRows(); ++j) {
            newTable.setValue(j, j + 1, data.getValue(j, j + 1));
          }

(上面的代码已经过测试,但不喜欢第二个 for() 循环,原因超出了我的理解)。

于 2013-01-18T02:54:13.110 回答