Accepted answer

All you need to do is create a new color scale

var colors = d3.scale.category20()

Associate each layer point with a fruit

var keys = ["redDelicious", "mcintosh", "oranges", "pears", "cherries", "plum","grapes", "melons"]

var dataset = d3.layout.stack()( {
  return {
    return {x: parse(d.year), y: +d[fruit], name: fruit};

And then start passing in fruit names during the data join.

var rect = groups.selectAll("rect")
  .data(function(d) { return d; })
  .style("fill", d=> colors(

The first time you pass in "apple" like var randomColor = colors('apple'), apple will be assigned a color. The next time you pass in apple, you will retrieve the same color.

For the legend, do adata join to create the rectangles, using the previously discussed color scale.

var legend = svg.selectAll(".legend")
  .attr("class", "legend")
  .attr("transform", function(d, i) { return "translate(30," + i * 19 + ")"; });

  .attr("x", width - 18)
  .attr("width", 18)
  .attr("height", 18)
  .style("fill", d=>colors(d));

  .attr("x", width + 5)
  .attr("y", 9)
  .attr("dy", ".35em")
  .style("text-anchor", "start")

Related Query

More Query from same tag