D3 Legend - Custom Styled

by Rishabh Sharma

HTML

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

JavaScript

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

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

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

var itemGroup = svg.append('g')
	.attr('class', 'items')
  .attr('transform', 'translate(0,20)');
  
var valGroup = svg.append('g')
	.attr('class', 'values')
  .attr('transform', 'translate(0,20)');
  
var lines = svg.append('g')
	.attr('class', 'lines')
  .attr('transform', 'translate(0,30)');
  
rects.selectAll('rect')
	.data(colors)
  .enter().append('rect')
  .attr('x', 20)
  .attr('y', function(d, i) {
  	return 35 * i;
  })
  .attr('width', 5)
  .attr('height', 30)
  .attr('fill', function(d) {
  	return d;
  });
  
itemGroup.selectAll('text')
	.data(items)
  .enter().append('text')
  .attr('x', 34)
  .attr('y', function(d, i) {
  	console.log(30 * i);
  	return 35 * i;
  })
  .text(function(d) {
  	return d;
  });
  
valGroup.selectAll('text')
	.data(values)
  .enter().append('text')
  .attr('x', 100)
  .attr('y', function(d, i) {
  	console.log(30 * i);
  	return 35 * i;
  })
  .text(function(d) {
  	return d;
  });
  
lines.selectAll('line')
 	.data(items)
  .enter()
  .append('line')
  .attr('x1', 20)
  .attr('y1', function(d, i) {
  	return 35 * i;
  })
  .attr('x2', 160)
  .attr('y2', function(d, i) {
  	return 35 * i;
  })
  .attr('stroke-width', 1)
  .attr('stroke', 'darkgray')
  .attr('stroke-dasharray', 2)