问题描述
我很高兴与,我试图创建相同的类型,参考那个小提琴。我的修改后的示例在中给出,我正在尝试创建如下视图。
I excited with this fiddle and I tried to create the same kind with reference to that fiddle. My modified sample is given in here and i'm trying to create a view as follows.
var distinctValues = data.getDistinctValues(2);
var viewColumns = [1];
var groupColumns = [];
// build column arrays for the view and grouping
for (var i = 0; i < distinctValues.length; i++) {
viewColumns.push({
type: 'number',
label: distinctValues[i],
aggregation: google.visualization.data.count
});
groupColumns.push({
column: i+1,
type: 'number',
//label: distinctValues[i],
aggregation: google.visualization.data.sum
});
}
但是我的目标是创建一个如下所示的数据透视表。 p>
But my aim is to create a pivot table something like as follows.
['Column1', 'Column2', 100, 200, 300, 400],
['A', 'bar', 0, 1, 1, 0],
['A', 'baz', 0, 0, 1, 0],
['A', 'foo', 3, 1, 0, 0],
['B', 'baz', 0, 1, 0, 0],
['B', 'cad', 1, 0, 1, 1],
['B', 'qud', 1, 1, 1, 2]
如何继续?
推荐答案
您必须在代码中更改一些内容。首先,如果要使Column1和Column2都在输出中,viewColumns需要同时包含0和1列。然后,您需要调整添加到viewColumns的列:每个需要一个calc参数来计算列中的值。在这种情况下,您希望将列的值与distinctValues [i]进行比较,并在匹配时返回1,否则返回0。在groupColumns的聚合函数中,使用sum而不是count:
You have to change a few things in your code. First, the viewColumns needs to contain both columns 0 and 1 to start if you want Column1 and Column2 to both be in the output. Then, you need to adjust the columns you add to the viewColumns: each one needs a calc parameter which calculates the value in the column. In this case, you want to compare the value of the column to distinctValues[i] and return 1 when they match and 0 when they don't. In the aggregation function for groupColumns, use sum instead of count:
var distinctValues = data.getDistinctValues(2);
var viewColumns = [0, 1];
var groupColumns = [];
// build column arrays for the view and grouping
for (var i = 0; i < distinctValues.length; i++) {
viewColumns.push({
type: 'number',
label: distinctValues[i],
calc: (function (x) {
return function (dt, row) {
return (dt.getValue(row, 2) == x) ? 1 : 0;
}
})(distinctValues[i])
});
groupColumns.push({
column: i+2,
type: 'number',
//label: distinctValues[i],
aggregation: google.visualization.data.sum
});
}
然后,在分组函数中,通过第一个数组中的列0和1 :
Then, in the grouping function, pass columns 0 and 1 in the first array:
var pivotedData = google.visualization.data.group(view,[0,1],groupColumns);
var pivotedData = google.visualization.data.group(view, [0, 1], groupColumns);
在这里查看这些变更:
See these changes working here: http://jsfiddle.net/asgallant/DUn6B/1/
这篇关于以编程方式摆脱Google Visualization dataTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!