gpt4 book ai didi

sum - 在 dc.js 中创建运行总和图

转载 作者:行者123 更新时间:2023-12-02 08:35:49 25 4
gpt4 key购买 nike

我正在尝试在 crossfilter 中创建运行总和以与 dc.js 一起使用。我有一组如下记录:

records = [{"date":"2014-01-01","field1":"value1","field2":"value11","value_field":-20},
{"date":"2014-01-02","field1":"value2","field2":"value12","value_field":100},
{"date":"2014-01-03","field1":"value1","field2":"value11","value_field":-10},
{"date":"2014-01-04","field1":"value2","field2":"value12","value_field":150},
]

到目前为止,我已经创建了一个 barGraph,它可以很好地与其他维度一起使用,但我希望能够显示理论字段 runnning_total(沿着维度日期)的折线图。

要在 crossfilter 中完成它,我可以使用 fieldx 字段进行分组,并轻松获得相同的运行总图,但使用 dc.js 限制为值的子组。

欢迎任何帮助。

最佳答案

由于您要跨日期分组(根据您的日期维度),reduce() 函数将用于执行聚合按日期分组,根据下面我的米老鼠示例中突出显示的单元格:

Aggregating across fruits

对于运行总计,您需要执行完全不同的操作,向下循环行:

enter image description here

您可以聚合数据,然后附加运行总计字段,如下所示。我还提供了一个示例,说明如何使用 reduce 函数计算平均值:

records = [{ "date": "2014-01-01", "field1": "value1", "field2": "value11", "value_field": -20 },
{ "date": "2014-01-02", "field1": "value2", "field2": "value12", "value_field": 100 },
{ "date": "2014-01-03", "field1": "value1", "field2": "value11", "value_field": -10 },
{ "date": "2014-01-04", "field1": "value2", "field2": "value12", "value_field": 150 }
];


var cf = crossfilter(records);

var dimensionDate = cf.dimension(function (d) {
return d.date;
});


function reduceAdd(p, v) {
p.total += v.value_field;
p.count++;
p.average = p.total / p.count;
return p;
}
function reduceRemove(p, v) {
p.total -= v.value_field;
p.count--;
p.average = p.count ? p.total / p.count : 0;
return p;
}
function reduceInitial() {
return {
total: 0,
count: 0,
average: 0,
};
}



var average = dimensionDate.group().reduce(reduceAdd, reduceRemove, reduceInitial).all();

var averageWithRunningTotal = appendRuningTotal(average);

function appendRuningTotal(average) {
var len = average.length,
runningTotal = 0;
for (var i = 0; i < len; i++) {
runningTotal += average[i].value.total;
average[i].RunningTotal = runningTotal;
}

return average;
}

这将返回以下内容:

{"key":"2014-01-01","value":{"total":-20,"count":1,"average":-20},"RunningTotal":-20}
{"key":"2014-01-02","value":{"total":100,"count":1,"average":100},"RunningTotal":80}
{"key":"2014-01-03","value":{"total":-10,"count":1,"average":-10},"RunningTotal":70}
{"key":"2014-01-04","value":{"total":150,"count":1,"average":150},"RunningTotal":220}

关于sum - 在 dc.js 中创建运行总和图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21698843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com