簡體   English   中英

Google使用圖例和其他顏色繪制API散點圖

[英]Google charts API scatter chart with legend and other colors

我有這樣一個例子:

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

當我將數據懸停一次時,工具提示會看到我這個數據的標簽。 那很好。

但是我想看到所有的值都是不同的顏色並放在圖例中。

例

怎么做?

散點圖的數據表中的列是圖例中顯示的列,並且顏色不同。 為了單獨顯示它們,您需要重新排列數據,以便每個人都有自己的列。

例如,用以下代碼替換數據表變量:

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

這樣做會給你想要的輸出(我相信,請點擊這里 )。

但是,這個方法的問題是你在每個系列中都會得到很多'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()循環)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM