score:2

Accepted answer

In a threshold scale, if the range has N values the domain has to have N - 1 values.

Therefore, just tell the scale exactly what you've told us in the question:

var color = d3.scaleThreshold()
    .domain([50, 250, 700])
    .range(["green", "yellow", "darkgreen", "yellow"]);

Here is a basic demo, hover over each rectangle to see its value:

var body = d3.select("body");
var color = d3.scaleThreshold()
  .domain([50, 250, 700])
  .range(["green", "yellow", "darkgreen", "yellow"]);
body.selectAll(null)
  .data(d3.range(51).map(d => d * 20))
  .enter()
  .append("div")
  .style("background-color", d => color(d))
  .on("mouseover", function(d) {
    console.log("value: " + d + ", color: " + color(d))
  })
div {
  min-width: 5px;
  min-height: 20px;
  display: inline-block;
  margin: 1px;
  border: 1px solid gray;
}

.as-console-wrapper { max-height: 30% !important;}
<script src="https://d3js.org/d3.v4.min.js"></script>


Related Query

More Query from same tag