我使用d3生成一个条形图,我有一些CSV数据,2015年的每一天都有4列。
我想要实现的是,只为1和2条表示12条,并在它们上添加一条线(我知道怎么做)。
那么,有人能向我解释一下,在不改变数据的情况下,如何只在一个月的第一天而不是每天显示条子呢?
发布于 2016-05-11 12:57:20
nest的d3特性将对您有所帮助。它的工作方式如下:为表中的每个条目提供一个键(这里的键是月份),并为具有相同键的每一组条目运行一个函数(在这里,取Bar和Bar的平均值)。这给出了一个表key -> value。
我假设您的日期表示为标准字符串“yyyy dd”。
var monthdata = d3.nest()
.key(function(d) {
//get month from data (first 7 characters):
return d.date.substring(0,7);})
.rollup(function(d) {
//run this function where d is a set of entries with same month
return {
bar1: d3.sum(d, function(g) {return g.bar1; }) / d.length, //average of bar1
bar2: d3.sum(d, function(g) {return g.bar2; }) / d.length //average of bar2
}
})
.entries(csv_data);此时,monthdata应该具有以下形式:
[{ key: "2015-01", values: {bar1: 123.4, bar2: 32.10} },
{ key: "2015-02", values: {bar1: 1234, bar2: 132.10} },
.. ]..。所有准备好插入到一个d3条形图。
https://stackoverflow.com/questions/37161815
复制相似问题