【问题标题】:Aggregate columns for Google ChartGoogle Chart 的聚合列
【发布时间】:2017-03-12 01:56:10
【问题描述】:

我尝试了几天没有成功聚合列。我也到处找,一无所获。我想将第 1 列(具有多个相同值的字符串)分组并对第 6、7、8 列(数字)求和,然后我想选择一个选项来显示第 6、7 或 8 列。

我希望我说得很清楚,并且一个解决方案可以帮助很多人。

下面我想分享一段代码。

这个例子类似:http://jsfiddle.net/guilhermelight1/fcqeA/80/

我也试过 calc: function()...

function drawVisualization() {
    var query = new google.visualization.Query('https://spreadsheets.google.com/tq?key=xxxxxx&sheet=data');

    query.setQuery("select B,I,J,O,P,Q,R,S,T where O is not null Order by Q desc ");
    query.send(handleQueryResponse);

    }


function handleQueryResponse(response) {
    if (response.isError()) {
    alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
    return;
    }

    var data = response.getDataTable();
       var tableChartB = new google.visualization.ChartWrapper({
    'chartType': 'Table',
        'containerId': 'table_divB',
                'options': {
                    'width': '100%'
                },
                'view': {'columns': [0,1,2,3,4,5,6,7,8]}
            }); 



var columnChart2 = new google.visualization.ChartWrapper({
          'chartType': 'ColumnChart',
          'containerId': 'Column_div',
          'view': {'columns': [1,6,7,8]},
        'options': {
            'bar': {'groupWidth': '95%'},
            'backgroundColor': 'transparent',
            'animation': {'duration': 1000, 'easing': 'out'},
            'legend': { 'position': 'top', 'alignment': 'start' },
            'width': '100%',
            'height': '90%',
            'chartArea': {'top': '10%', 'width': '85%','height': '80%' },
            'displayAnnotations': 'true',
           'hAxis': {'gridlines': { 'count': 40, 'color': 'transparent' } ,'textStyle':{'fontSize': 8.5}, 'slantedText': false, 'showTextEvery': 1,'minTextSpacing': 0,},
            'tooltip.isHtml': 'true',
            'pointSize': 2,
            'allowHtml': true,
            'vAxis': {'textStyle': {'fontSize': 9,'color': '#585858'},'minTextSpacing': 0},        
        //    'dataTable' : google.visualization.data.group(data, [1],[{'column': 8, 'aggregation': google.visualization.data.sum, 'type': 'number'}])

             }}); 


        google.visualization.events.addListener(tableChartB, 'ready',

            function(event) {
                // group the data of the filtered table and set the result in the pie chart.
                columnChart2.setDataTable( google.visualization.data.group(
                // get the filtered results
                tableChartB.getDataTable(),
                [1],
                [{'column': 6, 'aggregation': google.visualization.data.sum, 'type': 'number'},
                {'column': 7, 'aggregation': google.visualization.data.sum, 'type': 'number'},
                {'column': 8, 'aggregation': google.visualization.data.sum, 'type': 'number'}]
            ));
                // redraw the pie chart to reflect changes
                 columnChart2.draw();
            });

            google.visualization.events.addListener(tableChartB, 'statechange',

            function(event) {
                // group the data of the filtered table and set the result in the pie chart.
                columnChart2.setDataTable( google.visualization.data.group(
                // get the filtered results
                tableChartB.getDataTable(),
                [1],
                [{'column': 6, 'aggregation': google.visualization.data.sum, 'type': 'number'},
                {'column': 7, 'aggregation': google.visualization.data.sum, 'type': 'number'},
                {'column': 8, 'aggregation': google.visualization.data.sum, 'type': 'number'}]
            ));
                // redraw the pie chart to reflect changes
                columnChart2.draw();
            });


$('#subc').change(function () {
    var options = $("#subc option");
    var optionSelected = options.index(options.filter(":selected"));
    if (optionSelected === 0) {
        tableChartB.setView({
            'columns':  [0,1,2,3,4,5,6,7,8]
        });
        columnChart2.setView({
            'columns': [1,6,7,8 ]
        });
        columnChart2.setOption('colors', ["#FFC000","#00b0f0","#ff0000"]);


    } else if (optionSelected === 1) {
        tableChartB.setView({
            'columns':  [0,1,2,3,4,5,6,7,8]
        });
        columnChart2.setView({
            'columns': [1,{
'type': 'number',
'label': 'Average',
'calc': function (dt, row) {
    return group.getValue(0, 1);
}, 6 ]
        });
        columnChart2.setOption('colors', ["#FFC000"]);


    } else if (optionSelected === 2) {
        tableChartB.setView({
            'columns':  [0,1,2,3,4,5,6,7,8]
        });
        columnChart2.setView({
            'columns': [1,7]
        });
       columnChart2.setOption('colors', ["#00b0f0"]);

    } else if (optionSelected === 3) {
        tableChartB.setView({
            'columns':  [0,1,2,3,4,5,6,7,8]
        });
        columnChart2.setView({
            'columns': [1,8 ]
        });
        columnChart2.setOption('colors', ["#ff0000"]);

     } else {
        tableChartB.setView({
            'columns':  [0,1,2,3,4,5,6,7,8]
        });
        columnChart2.setView({
            'columns': [1,6,7,8 ]
        });
        columnChart2.setOption('colors', ["#FFC000","#00b0f0","#ff0000"]);
    }

    drawChart();
});

}

     <label class="google-visualization-controls-label"></label>
     <select id="subc" class="filter">
     <option selected="selected" value="a1">Dia-h</option>
                <option value="a2">Dia</option>
                <option value="a3">Calendário</option>
                <option value="a4">Hora</option>
      </select>

【问题讨论】:

    标签: google-apps-script google-visualization


    【解决方案1】:

    不确定我是否完全遵循这个问题,请参阅以下工作 sn-p...

    根据张贴的小提琴调整...

    google.charts.load('current', {
      callback: drawVisualization,
      packages:['controls']
    });
    
    function drawVisualization() {
      // Prepare the data
      var jsonData = '{"cols":[{"label":"Subject","type":"string"},{"label":"pete","type":"number"},{"label":"john","type":"number"},{"label":"carl","type":"number"},{"label":"andrea","type":"number"}],"rows":[{"c":[{"v":"coolness"},{"v":4.4},{"v":4.3},{"v":3.1},{"v":4.3}]},{"c":[{"v":"sexyness"},{"v":4.2},{"v":3.8},{"v":3.6},{"v":4.8}]},{"c":[{"v":"toughness"},{"v":3.1},{"v":2.7},{"v":2.4},{"v":2.9}]},{"c":[{"v":"chillnes"},{"v":4.4},{"v":4.4},{"v":4.2},{"v":4.5}]},{"c":[{"v":"madness"},{"v":4.6},{"v":4.6},{"v":4},{"v":4.6}]},{"c":[{"v":"lochness"},{"v":3.9},{"v":3.7},{"v":2.9},{"v":3.9}]},{"c":[{"v":"extraness"},{"v":4.6},{"v":4.3},{"v":3.6},{"v":4.3}]},{"c":[{"v":"extraness"},{"v":4.6},{"v":4.3},{"v":3.6},{"v":4.3}]}]}';
    
      var data = new google.visualization.DataTable(JSON.parse(jsonData));
    
      var compPicker = new google.visualization.ControlWrapper({
        'controlType': 'CategoryFilter',
        'containerId': 'control2',
        'options': {
          'filterColumnLabel': 'Subject',
          'ui': {
          'labelStacking': 'vertical',
            'allowTyping': false,
            'allowMultiple': true
          }
        }
      });
      // Define a chart
      var chart = new google.visualization.ChartWrapper({
          'chartType': 'ColumnChart',
          'containerId': 'chart1',
          'options': {'title':'Competenties',
            'width':'100%',
            'height':300,
            'vAxis': {
              viewWindow: {max:5,min:0},
              gridlines: {color:'#CCC', count: 6}
            },
            bar: { groupWidth: '80%' },
            colors: ["#FFC000","#00b0f0","#ff0000","#92d050"]
          }
      });
    
      // Define a table
      var table = new google.visualization.ChartWrapper({
        'chartType': 'Table',
        'containerId': 'chart2',
        'options': {
          'width': '400px'
        }
      });
    
      var groupData;
      var groupTable = new google.visualization.ChartWrapper({
          chartType: 'Table',
          containerId: 'chart3',
          options: {
            width: 400
          }
        });
      google.visualization.events.addListener(table, 'ready', function() {
        groupData = google.visualization.data.group(
          table.getDataTable(),
          [0],
          [
            {
              aggregation: google.visualization.data.sum,
              column: 1,
              label: data.getColumnLabel(1),
              type: 'number'
            },
            {
              aggregation: google.visualization.data.sum,
              column: 2,
              label: data.getColumnLabel(2),
              type: 'number'
            },
            {
              aggregation: google.visualization.data.sum,
              column: 3,
              label: data.getColumnLabel(3),
              type: 'number'
            },
            {
              aggregation: google.visualization.data.sum,
              column: 4,
              label: data.getColumnLabel(4),
              type: 'number'
            }
          ]
        );
        groupTable.setDataTable(groupData);
        groupTable.draw();
      });
    
      // Create a dashboard
      var drawChart = new google.visualization.Dashboard(document.getElementById('dashboard')).bind([compPicker], [chart, table]);
      drawChart.draw(data);
    
      document.getElementById('names').addEventListener('change', function (evt) {
        var colors = ["#FFC000", "#00b0f0", "#ff0000", "#92d050"];
        var viewColumns = {columns: []};
        var viewColors = [];
        switch (evt.target.selectedIndex) {
          case 0:
            $.each(new Array(evt.target.options.length), function (index) {
              viewColumns.columns.push(index);
              if (index > 0) {
                viewColors.push(colors[index - 1]);
              }
            });
            break;
    
          default:
            viewColumns.columns.push(0);
            viewColumns.columns.push(evt.target.selectedIndex);
            viewColors.push(colors[evt.target.selectedIndex - 1]);
        }
        chart.setView(viewColumns);
        chart.setOption('colors', viewColors);
        groupTable.setView(viewColumns);
        drawChart.draw(data);
      }, false);
    }
    <script src="https://www.gstatic.com/charts/loader.js"></script>
    <div id="dashboard">
    	<select id="names">
    		<option value="0">all</option>
    		<option value="1">pete</option>
    		<option value="2">john</option>
    		<option value="3">carl</option>
    		<option value="4">andrea</option>
    	</select>
    	<table>
    		<tr style='vertical-align: top'>
    			<td>
    				<div id="control1"></div>
    				<div id="control2"></div>
    				<div id="control3"></div>
    			</td>
    		</tr>
    		<tr>
    			<td>
    				<div style="float: left;" id="chart1"></div>
    				<div style="float: left;" id="chart2"></div>
    				<div style="float: left;" id="chart3"></div>
    			</td>
    		</tr>
    	</table>
    </div>

    【讨论】:

    • 感谢您帮助我...您的示例没有准确分组为宠物/额外...我确实更新了一个工作示例jsfiddle.net/guilhermelight1/fcqeA/82...但是对于我的代码我没有解决问题。
    • 据我所知,上面的例子确实分组了extraness,只是排序不同...
    • 我可能没有正确表达。如果您选择 pet 和 extraness.. 您可以看到 sum 为 1 bar 而不是 2 bar..
    • 不跟随,使用分组功能时,extraness合并为一行,因为两行有相同的subject
    • 主题是 9.2(总和)...我想在图表列中看到这个结果...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-10
    • 1970-01-01
    相关资源
    最近更新 更多