Reputation: 3376
Take this simple grouped column chart. The data values are passed in this format:
{
"Group1": [group1_subvalue1, group1_subvalue2.....],
"Group2": [group2_subvalue1, group2_subvalue2.....],
....
}
I'd like to sort each group individually, i.e.: for each state, order the columns from taller to narrower. But I'm unable to find a way to do it. In the given example, the array for each group must be in the same order (first people under 5 y.o, 5 to 13 after that, and so on), so I don't know how to face the problem.
Upvotes: 0
Views: 1216
Reputation: 1998
To show how to sort each group individually, I took Mike Bostock's example to adjusted it accordingly. You have to do the following things:
You sort the within-group categories (in the example it's the d.ages Array)
d.ages.sort(function(a, b) { return d3.ascending(a.value, b.value); });
x1 is your scale for the within group categories. Instead of mapping the categories to the same relative position, you just map the index of your sorted array to the x position. d3.range() creates an array which is your domain.
x1.domain(d3.range(0, data[0].ages.length)).rangeRoundBands([0, x0.rangeBand()]);
When you draw, you just call the index instead of the category
.attr("x", function(d, i) { return x1(i); })
The full working example is here. I have also added how to sort the groups.
Upvotes: 2