score:1

Accepted answer

http://jsfiddle.net/ve38098w/

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()(keys.map(function(fruit) {
  return data.map(function(d) {
    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; })
  .enter()
  .append("rect")
  ...
  .style("fill", d=> colors(d.name))

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")
  .data(keys)
  .enter().append("g")
  .attr("class", "legend")
  .attr("transform", function(d, i) { return "translate(30," + i * 19 + ")"; });

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

legend.append("text")
  .attr("x", width + 5)
  .attr("y", 9)
  .attr("dy", ".35em")
  .style("text-anchor", "start")
  .text(d=>d);

Related Query

More Query from same tag