D3 Legend Component by Susie Lu

HTML

<script src="//d3js.org/d3.v3.min.js"></script>
<script src="//rawgit.com/susielu/d3-legend/master/d3-legend-all.min.js"></script>
<link rel="stylesheet" href="//rawgit.com/susielu/minimal-ui/master/minimal-ui.min.css">
<svg height=200></svg>
<svg id="color-linear"></svg>
<svg id="color-ordinal"></svg>

CSS

.legendSize rect, .legendSize circle{
  fill: rgb(46, 73, 123);
}


.legendSizeHorz circle{
  stroke: rgb(71, 187, 94);
  fill: none;
}
text {
  font-size: 10px;
}

 .legendSizeHorz line {
  stroke: rgb(46, 73, 123);
 }

 .legendPath path {
  fill: rgb(71, 187, 94);
 }

.q0-9 { fill:rgb(247,251,255); }
.q1-9 { fill:rgb(222,235,247); }
.q2-9 { fill:rgb(198,219,239); }
.q3-9 { fill:rgb(158,202,225); }
.q4-9 { fill:rgb(107,174,214); }
.q5-9 { fill:rgb(66,146,198); }
.q6-9 { fill:rgb(33,113,181); }
.q7-9 { fill:rgb(8,81,156); }
.q8-9 { fill:rgb(8,48,107); }

JavaScript

svg = d3.select("svg")
var quantize = d3.scale.quantize()
  .domain([ 0, 0.15 ])
  .range(d3.range(9).map(function(i) { return "q" + i + "-9"; }));

svg.append("g")
  .attr("class", "legendQuant")
  .attr("transform", "translate(20,20)");

var legend = d3.legend.color()
  .labelFormat(d3.format(".2f"))
  .useClass(true)
  .scale(quantize);

svg.select(".legendQuant")
  .call(legend);

var linear = d3.scale.linear()
  .domain([0,10])
  .range(["rgb(46, 73, 123)", "rgb(71, 187, 94)"]);

var svg = d3.select("#color-linear");

svg.append("g")
  .attr("class", "legendLinear")
  .attr("transform", "translate(20,20)");

var legendLinear = d3.legend.color()
    .shapeWidth(20)
    .shapePadding(0)
    .cells(6)
    .orient('horizontal')
    .scale(linear);

svg.select(".legendLinear")
  .call(legendLinear);

var ordinal = d3.scale.ordinal()
  .domain(["a", "b", "c", "d", "e"])
  .range([ "rgb(153, 107, 195)", "rgb(56, 106, 197)", "rgb(93, 199, 76)", "rgb(223, 199, 31)", "rgb(234, 118, 47)"]);

svg = d3.select("#color-ordinal");

svg.append("g")
  .attr("class", "legendOrdinal")
  .attr("transform", "translate(20,20)");

var legendOrdinal = d3.legend.color()
  //d3 symbol creates a path-string, for example
  //"M0,-8.059274488676564L9.306048591020996,
  //8.059274488676564 -9.306048591020996,8.059274488676564Z"
  .shape("path", d3.svg.symbol().type("triangle-up").size(150)())
  .shapePadding(10)
  .scale(ordinal);

svg.select(".legendOrdinal")
  .call(legendOrdinal);