From 8b14d1f9de1c3b7088138dfb25bf77a4ab83b0b7 Mon Sep 17 00:00:00 2001 From: mhodorogea Date: Mon, 17 Nov 2014 10:44:06 +0100 Subject: [PATCH] Fix ordering option for the barChart. Tests have been added to show the reliability of the feature. --- spec/bar-chart-spec.js | 58 ++++++++++++++++++++++++++++++++++++++++++ src/stack-mixin.js | 8 +++++- 2 files changed, 65 insertions(+), 1 deletion(-) diff --git a/spec/bar-chart-spec.js b/spec/bar-chart-spec.js index ab9afb21f..17652472e 100644 --- a/spec/bar-chart-spec.js +++ b/spec/bar-chart-spec.js @@ -951,6 +951,64 @@ describe('dc.barChart', function() { }); }); + describe('check ordering option of the x axis', function() { + beforeEach(function() { + var rows = [ + {x: 'a', y: 1}, + {x: 'b', y: 3}, + {x: 'd', y: 4}, + {x: 'c', y: 2} + ]; + + id = 'bar-chart'; + appendChartID(id); + data = crossfilter(rows); + dimension = data.dimension(function(d) { + return d.x; + }); + group = dimension.group().reduceSum(function(d) { + return d.y; + }); + + chart = dc.barChart('#' + id); + chart.width(500).transitionDuration(0) + .x(d3.scale.ordinal()) + .xUnits(dc.units.ordinal) + .elasticY(true).elasticX(true) + .dimension(dimension) + .group(group); + chart.render(); + }); + + it('should be ordered by default alphabetical order', function() { + var data = chart.data()["0"].values; + var expectedData = ["a", "b", "c", "d"]; + expect(data.map(function(d) { return d.x; })).toEqual(expectedData); + }); + + it('should be ordered by value increasing', function() { + chart.ordering(function(d) { return d.data.value; }); + chart.redraw(); + expect(xAxisText()).toEqual(["a", "c", "b", "d"]); + }); + + it('should be ordered by value decreasing', function() { + chart.ordering(function(d) { return -d.data.value; }); + chart.redraw(); + expect(xAxisText()).toEqual(["d", "b", "c", "a"]); + }); + + it('should be ordered by alphabetical order', function() { + chart.ordering(function(d) { return d.data.key; }); + chart.redraw(); + expect(xAxisText()).toEqual(["a", "b", "c", "d"]); + }); + + function xAxisText() { + return chart.selectAll("g.x text")[0].map(function(x) { return d3.select(x).text(); }); + } + }); + function nthStack(n) { var stack = d3.select(chart.selectAll(".stack")[0][n]); diff --git a/src/stack-mixin.js b/src/stack-mixin.js index d08e6d9ad..6f3ff7d8e 100644 --- a/src/stack-mixin.js +++ b/src/stack-mixin.js @@ -170,7 +170,13 @@ dc.stackMixin = function (_chart) { }; function flattenStack() { - return _chart.data().reduce(function (all, layer) { + var groups = _chart.data(); + + if(groups.length){ + groups[0].values = _chart._computeOrderedGroups(groups[0].values); + } + + return groups.reduce(function (all, layer) { return all.concat(layer.values); }, []); }