var legendRectSize = 15;
var legendSpacing = 4;
function makeLegend(){
	
	d3.select("#legend-title").text(function(d){
		if (colorBy == "ep") {
			return "Epitope mutations"
		}
		if (colorBy == "ne") {
			return "Non-epitope mutations"
		}
		if (colorBy == "rb") {
			return "Receptor binding mutations"
		}
		if (colorBy == "lbi") {
			return "Local branching index"
		}
   if (colorBy == "region") {
     return "Region"
   }
   if (colorBy == "genotype") {
     return "Genotype"
   }
   if (colorBy == "dfreq") {
    var tmp_nmonth = Math.round(12*dfreq_dn*time_step);
    var tmp_text = "Freq. change ("+tmp_nmonth+" month";
      if (tmp_nmonth>1){
       tmp_text+='s';
     }
     return tmp_text+')';
}
});

  var tmp_leg = legend.selectAll(".legend")
  .data(colorScale.domain())
  .enter().append('g')
  .attr('class', 'legend')
  .attr('transform', function(d, i) {
   var stack = 5;
   var height = legendRectSize + legendSpacing;
   var fromRight = Math.floor(i / stack);
   var fromTop = i % stack;
   var horz = fromRight * 145 + 5;				
   var vert = fromTop * height + 5;
   return 'translate(' + horz + ',' + vert + ')';
 });
  tmp_leg.append('rect')
  .attr('width', legendRectSize)
  .attr('height', legendRectSize)
  .style('fill', function (d) {
   var col = colorScale(d);
   return d3.rgb(col).brighter([0.35]).toString();
 })
  .style('stroke', function (d) {
   var col = colorScale(d);
   return d3.rgb(col).toString();
 });

  tmp_leg.append('text')
  .attr('x', legendRectSize + legendSpacing + 5)
  .attr('y', legendRectSize - legendSpacing)
  .text(function(d) {
   return d.toString().replace(/([a-z])([A-Z])/g, '$1 $2').replace(/,/g, ', ');
 });		
  return tmp_leg;
}

function removeLegend(){
	legend.selectAll('.legend')
  .remove();
}


@@ -158,32 +158,33 @@
 itope mutations%22
+;
 %0A%09%09%7D%0A%09%09if (color
@@ -222,32 +222,33 @@
 itope mutations%22
+;
 %0A%09%09%7D%0A%09%09if (color
@@ -299,16 +299,17 @@
 tations%22
+;
 %0A%09%09%7D%0A%09%09i
@@ -368,16 +368,16 @@
 dex%22
+;
 %0A%09%09%7D%0A
-   
+%09%09
 if (
@@ -395,29 +395,27 @@
 %22region%22) %7B%0A
-     
+%09%09%09
 return %22Regi
@@ -417,25 +417,24 @@
 %22Region%22
-%0A   %7D%0A   
+;%0A%09%09%7D%0A%09%09
 if (colo
@@ -454,21 +454,19 @@
 ype%22) %7B%0A
-     
+%09%09%09
 return %22
@@ -478,17 +478,73 @@
 ype%22
-%0A   %7D%0A   
+;%0A%09%09%7D%0A%09%09if (colorBy == %22date%22) %7B%0A%09%09%09return %22Years back%22;%0A%09%09%7D%09%09%0A%09%09
 if (
@@ -565,20 +565,19 @@
 req%22) %7B%0A
-    
+%09%09%09
 var tmp_
@@ -620,20 +620,19 @@
 _step);%0A
-    
+%09%09%09
 var tmp_
@@ -676,22 +676,19 @@
 month%22;%0A
-      
+%09%09%09
 if (tmp_
@@ -702,15 +702,12 @@
 1)%7B%0A
-       
+%09%09%09%09
 tmp_
@@ -721,20 +721,16 @@
 s';%0A
-     %7D%0A     
+%09%09%09%7D%0A%09%09%09
 retu
@@ -746,16 +746,18 @@
 xt+')';%0A
+%09%09
 %7D%0A%7D);%0A%0A 

Add legend title for dates.