Google使用图例和其他颜色绘制API散点图

时间:2013-01-17 14:54:08

标签: javascript google-api google-visualization

我有一个例子:

// 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/

当我将数据悬停一次时,工具提示会看到我这个数据的标签。那很好。

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

example

怎么做?

1 个答案:

答案 0 :(得分:7)

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

例如,用以下代码替换您的数据表变量:

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

执行此操作将为您提供所需的输出(我相信,请检查here)。

然而,这个方法的问题是你在每个系列中都会得到很多'null'值(因为你只有一个点)。为了简化此过程,您可以编写一个循环来遍历数据并为新表格格式化。基本代码是:

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

              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()循环,原因超出了我的理解范围。)