Илья Book Nerd
Илья Book Nerd

Reputation: 23

my own d3 custom color scale - interpolate a range from one given HEX to another

I cannot create a custom color scale. I want d3 to interpolate a range from one hex to another

  const colorRange = ['#d7191c', '#d55045']
  const data = [617, 631, 640, 650]
  const color = d3
    .scaleLinear()
    .domain(1, data.length)
    .interpolate(d3.interpolateHcl)
    .range([d3.hcl(colorRange[1]), d3.hcl(colorRange[0])])
  console.log(color(1)) // returns 'rgb(0,0,0)' but expected some hex from the gradient from '#d55045' to '#d7191c'

Upvotes: 1

Views: 1561

Answers (1)

rioV8
rioV8

Reputation: 28653

You need to specify the domain correctly

const colorRange = ['#d7191c', '#d55045']
const data = [617, 631, 640, 650]
const color = d3.scaleLinear()
  .domain([1, data.length])
  .interpolate(d3.interpolateHcl)
  .range([d3.hcl(colorRange[1]), d3.hcl(colorRange[0])])
console.log(color(1));
<script src="https://d3js.org/d3.v5.min.js"></script>

Upvotes: 2

Related Questions