javascriptreactjsd3.js

How to simply generate N colors?


I'm using D3 7.9 and can't find a way to simply generate N colors, for example, from rainbow. How do you do that outside the D3 way of doing things?

For example;

const categories = ['a', 'b', 'c', ..., ]
const n = parseFloat(categories.length);
const colors = d3.sequentialScale(d3.rainbowInterpolation);
const palette = categories.reduce((acc, category, i) => {
    return Object.assign(acc, {[category]: colors(parseFloat(i) / n});
 }

Solution

  • Consider utilizing interpolateRainbow:

    const N = 7;
    const colors = Array.from({ length: N }, (_, i) => d3.interpolateRainbow(i / N));
    const container = d3.select("#color-container");
    container.selectAll(".color-box")
      .data(colors)
      .enter()
      .append("div")
      .attr("class", "color-box")
      .style("background-color", d => d);
    .color-box {
      display: inline-block;
      width: 50px;
      height: 50px;
      margin: 5px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.9.0/d3.min.js"></script>
    <div id="color-container"></div>

    If you for some reason only have access to interpolateRgb try something like this:

    const N = 7;
    const startColor = "red";
    const endColor = "blue";
    const interpolate = d3.interpolateRgb(startColor, endColor);
    const colors = Array.from({ length: N }, (_, i) => interpolate(i / N));
    console.log(colors);
    const colorsHex = colors.map(color => d3.rgb(color).formatHex());
    console.log(colorsHex);
    .as-console-wrapper { max-height: 100% !important; top: 0; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.9.0/d3.min.js"></script>