Reputation: 39
Iam working in Crossfilter with dc.js,
i have to get Average of Units for each day of week in bar chart. i have date and units column and i have tried getting DOW(Dayofweek) from Date and with that DOW i tried getting average of the Units, but not working. i have attached my code here, please help me out.
d3.csv("LargeCSVFile.txt", function (error, data) {
var dayOfWeekChart = dc.barChart("#dc2");
var dateFormat = d3.time.format('%m/%d/%Y');
var ndx = crossfilter(data);
var all = ndx.groupAll();
var dayOfWeek = ndx.dimension(function (d) {
var dateval = dateFormat.parse(d.Date);
var day = dateval.getDay();
return day;
});
var AVGUnitsDimGroup = dayOfWeek.group().reduce(
//add
function (p, v) {
++p.count;
p.sum = v.Units;
p.avg = p.sum / p.count;
return p;
},
//remove
function (p, v) {
--p.count;
p.sum = v.Units;
p.avg = p.sum / p.count;
return p;
},
//init
function (p, v) {
return {
count: 0,
avg: 0,
sum: 0
};
});
dayOfWeekChart.width(180)
.height(180)
.margins({ top: 20, left: 10, right: 10, bottom: 20 })
.dimension(dayOfWeek)
.group(AVGUnitsDimGroup)
.x(d3.scale.linear().domain([0.5, 7.5]))
.label(function (d) {
return d.key;
})
.title(function (d) {
return d.value.avg;
})
.elasticX(true)
.xAxis().ticks(4);
dc.renderAll();
})
Upvotes: 1
Views: 107
Reputation: 39
I have solved it myself, I forgot to add the sum values and adding .valueAccessor(function (p) { return p.value.avg; }) next to group function made my code to work properly. here is my working code.
d3.csv("LargeCSVFile.txt", function (error, data) {
var dayOfWeekChart = dc.barChart("#dc2");
data.forEach(function (d) {
d.dd = new Date(d.Date);
});
var ndx = crossfilter(data);
var all = ndx.groupAll();
var dayOfWeek = ndx.dimension(function (d) {
return d.dd.getDay();
});
var AVGUnitsDimGroup = dayOfWeek.group().reduce(
//add
function (p, v) {
++p.count;
p.sum += v.Units / 1;
p.avg = p.sum / p.count;
return p;
},
//remove
function (p, v) {
--p.count;
p.sum += v.Units / 1;
p.avg = p.sum / p.count;
return p;
},
//init
function (p, v) {
return {
count: 0,
sum: 0,
avg: 0
};
});
dayOfWeekChart.width(400)
.height(300)
.margins({ top: 20, left: 50, right: 10, bottom: 20 })
.transitionDuration(1500)
.dimension(fluctuation)
.group(AVGUnitsDimGroup)
.valueAccessor(function (p) {
return p.value.avg;
})
.x(d3.scale.ordinal().domain([1,2,3,4,5,6,7]))
.xUnits(dc.units.ordinal)
.title(function (d) {
return d.value.avg;
})
.xAxisPadding(600)
.elasticX(true)
.elasticY(true)
.xAxis().ticks();
dc.renderAll();
})
Upvotes: 1