<div>Simple gradient</div>
<div id="viz"></div>
<div>Multicolor viz</div>
<div id="multicolor-viz"></div>
'use strict';
let width = 400, height = 50;
    
/* 
    Simple gradient example    
*/
let colors= [ '#ffeeff', '#00dd00']; //  gradient's colors

let color = d3.scaleLinear()
  .domain([0,1])
  .range(colors);

// add svg element to body

let svg = d3.select('#viz').append('svg')
  .attr('width', width)
  .attr('height', height);

// add linearGradient's defs to svg 

let gradient = svg.append('defs')
  .append('linearGradient')
  .attr('id', 'gradient')
  .attr('x1', '0%')
  .attr('y1', '0%')
  .attr('x2', '100%')
  .attr('y2', '0%');

/* 
    add "stop" colors.
    property "offset" set when in gradient srart to use this color in gradient:
    0% - from very beginning
    100% - end;
 */

gradient.append('stop')
    .attr('offset', '0%')
    .attr('stop-color', colors[0])
    .attr('stop-opacity', 1);

gradient.append('stop')
    .attr('offset', '100%')
    .attr('stop-color', colors[1])
    .attr('stop-opacity', 1);

// add gradient to element

let rect = svg.append('rect')
  .attr('width', '100%')
  .attr('height', '20')
  .attr('x','10')
  .attr('y','10')
  .style('fill', 'url(#gradient)');

// select color from gradient depends on value

let val = 0.5; // change this value and you see changes in bottom rectangle's color

svg.append('rect')
  .attr('width', '20')
  .attr('height', '20')
  .attr('x','10')
  .attr('y','30')
  .style('fill', ()=>color(val))
  .text(val);

/*---------------------
  Multicolor Example
----------------------*/

let svg2 = d3.select('#multicolor-viz').append('svg')
  .attr('width', width)
  .attr('height', '100'),
   /* 
   Set array of colors, ordered. first element will be set to offset 0%, last one to offset 100%. 
   Others' offset depend to their position in array.  
   */
   multicolors = [ 'lightgreen', 'yellow', 'red'];

// add linearGradient's defs to svg 

let gradient2 = svg2.append('defs')
  .append('linearGradient')
  .attr('id', 'gradient2')
  .attr('x1', '0%')
  .attr('y1', '0%')
  .attr('x2', '100%')
  .attr('y2', '0%');

// add "stop" colors

gradient2.selectAll('stop')
  .data(multicolors)
  .enter().append('stop')
    .attr('offset', (d,i)=>i/(multicolors.length-1))
    .attr('stop-color', (d)=>d)
    .attr('stop-opacity', 1);

// add new legend bar
svg2.append('rect')
  .attr('width', '100%')
  .attr('height', '100')
  .attr('x','10')
  .attr('y','10')
  .style('fill', 'url(#gradient2)');
View Compiled
Rerun