Home > Enterprise >  How to assign colors to more than 10 objects of an array in JavaScript?
How to assign colors to more than 10 objects of an array in JavaScript?

Time:11-17

I have an array of length 32 containing names and I want each of them has an unique color.

I used colors = d3.scaleOrdinal(sorted_artists, d3.schemeTableau10) but it only gives me 10 colors which would be repetitive.

Then I found with this colors = d3.scaleOrdinal().domain(sorted_artists).range(["gold", "blue", "green", "yellow", "black", "grey", "darkgreen", "pink", "brown", "slateblue", "grey1", "orange"])

Should I use secound one and add more color to have 32 colors manually? or we have something predefined like the first one?

CodePudding user response:

if random color is ok, how about this way?

let randomPalette = [...new Array(32)].map(() => d3.interpolateSinebow(Math.random()));
let colors = d3.scaleOrdinal().domain(['a','b','c','d','e','f','g','h','i','j']).range(randomPalette)

console.log(randomPalette)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

  • Related