BlackMath
BlackMath

Reputation: 992

How to keep the order of slices fixed in a pie chart? [d3]

I have this array of objects

const data = [
 {id: 0, type: "inc", amount: 3000},
 {id: 1, type: "exp", amount: 1500}
]

When I pass this data to a d3 pie function

const pie = d3.pie().value(d => d.amount);

the inc entry will have index: 0 while exp entry will have index: 1. My understanding, d3 by default assign the largest value index 0, which means startAngle will be 0 for the largest value, and goes on in descending order of the values.

In my case, the application can change the amount of either entry. The default behavior of d3 swaps the order of inc and exp in the pie chart once exp amount exceeds that of inc. I want the entry of type inc to always start from startAngle 0, even if exp entry's amount exceeds that of inc entry. How can I achieve this?

Upvotes: 3

Views: 497

Answers (1)

BlackMath
BlackMath

Reputation: 992

To those who are interested in the answer, it turned out you can define a compare function inside the sort method of the pie function like so

const pie = d3.pie().value(d => d.amount).sort((a) => {
      if (a.type === 'inc') {
        return -1;
      } else {
        return 1;
      }
    });

This will keep the inc entry with index: 0 all the time, regardless of the amount value compared to the exp entry

Upvotes: 2

Related Questions