D3 Legend

by Rishabh Sharma

HTML

<script src="https://d3js.org/d3.v4.js"></script>
<svg height="300" width="300"></svg>

JavaScript

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

var colors = ['#D8A6FC', '#AFDEDC', '#E5E6E4'];
var items = ['Item 1', 'Item 2', 'Item 3']

var circles = svg.append('g')
	.attr('class', 'circles');

var itemGroup = svg.append('g')
	.attr('class', 'items');
  
circles.selectAll('circle')
	.data(colors)
  .enter().append('circle')
  .attr('cx', 20)
  .attr('cy', function(d, i) {
  	return 40 * (i  + 1);
  })
  .attr('r', 10)
  .attr('fill', function(d) {
  	return d;
  });
  
itemGroup.selectAll('text')
	.data(items)
  .enter().append('text')
  .attr('x', 34)
  .attr('y', function(d, i) {
  	return 42 * (i+1);
  })
  .text(function(d) {
  	return d;
  });