You are here: Home » NewsFeeds » Legends in D3

Legends in D3

Examples

Quantile Scale Legend

          

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

var svg = d3.select("svg");

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);
          
        

Linear Scale Legend – Horizontal

          

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

var svg = d3.select("svg");

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

var legendLinear = d3.legend.color()
  .shapeWidth(30)
  .orient('horizontal')
  .scale(linear);

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

Linear Scale Legend – 10 cells

          

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

var svg = d3.select("svg");

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

var legendLinear = d3.legend.color()
  .shapeWidth(30)
  .cells(10)
  .orient('horizontal')
  .scale(linear);

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

Linear Scale Legend – Custom cells

          

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

var svg = d3.select("svg");

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

var legendLinear = d3.legend.color()
  .shapeWidth(30)
  .cells([1, 2, 3, 6, 8])
  .orient('horizontal')
  .scale(linear);

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

Ordinal Scale Legend – Custom shape

          

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)"]);

var svg = d3.select("svg");

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);
          
        


 

Original article