1
votes

I'm drawing a pie using d3, and using the following to fill the slices with certain colors:

d3.scale.ordinal().domain([]).range(['#2ECC71', '#208E4E', '#12512C', '#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'])

My problem arises when swapping out one pie chart for another, which is in essence just a data swap. When doing so, instead of the new pie starting from '#2ECC71', it starts from a later color value, depending on how many slices there were; e.g. if two slices were used, the "new" pie after dataswap would start at "#12512c".

js framework: Vue.js d3 version: v3

Cheers.

1
Okay, so I figured out the problem: domain arguments. const greenScale = ['#2ECC71', '#208E4E', '#12512C', '#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']; First I tried d3.scale.ordinal().domain([0, greenScale.length]).range(greenScale) But that didn't work. My pie charts were skipping from the first value to the fourth. That said, I went back to the docs and noticed that the domain values can be mapped 1-1 to the range values. Solution: d3.scale.ordinal().domain(_.range(greenScale.length)).range(greenScale) - Santboi

1 Answers

1
votes

I imagine you'll be calling the scale function and passing the value. If you have have a category key or data array index key you'll get consistent results.

See in the example below passing pretend values into the scale function returns new colour values each time. As its assigning a new value to the key. While passing the same value (string or int) always returns the same result.

let colorScale = d3.scale.ordinal().domain([]).range(['#2ECC71', '#208E4E', '#12512C', '#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'])

// new colour for each value
console.log(colorScale(50))
console.log(colorScale(10))
console.log(colorScale(100))

// new colours for each index
console.log(0, colorScale(0))
console.log(1, colorScale(1))
console.log(2, colorScale(2))

// using the colours already assigned to keys 0,1
console.log(0, colorScale(0))
console.log(1, colorScale(1))

// alternatively use category key values
console.log('Africa', colorScale('Africa'))
console.log('Africa', colorScale('Africa'))

console.log('America', colorScale('America'))
console.log('Australia', colorScale('Australia'))

console.log('America', colorScale('America'))
console.log('Australia', colorScale('Australia'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>