D3 interpolate type and SVG Group Element

We can’t add text to a rectangle or any shape to any other shape in the SVG. In standard HTML we can put almost or any element inside another element, eg we can add table an element inside the div element.

There are some exception element in SVG, eg TSPAN can be added inside the text element. The SVG group element allows us to add anything inside the group include group inside another group. The SVG group element can be used to group another SVG element together and it acts as a container for another SVG element.  By nature group, an element is not shown in the web browser, as itself can’t be style. But group element has the tangible effect, the group content can be conceptual move, rotate its content.

The group element allows us to join another element together, turn then in pink or move to new pixel and they allow us to tight organize the elements in the DOM. In the example below, we had used different interpolate available in D3 and we had created 6 group element and each group is having path information and six dots as the circle on the path.

var dataArray = [{x:5,y:5},{x:10,y:15},{x:20,y:7},{x:30,y:18},{x:40,y:10}];
var interpolateTypes = [d3.curveLinear,d3.curveNatural,d3.curveStep,d3.curveBasis,d3.curveBundle,d3.curveCardinal];

var svg = d3.select("body").append("svg").attr("height","100%").attr("width","100%");


for(var p=0; p<6; p++){
	var line = d3.line()
					.x(function(d,i){ return d.x*6; })
					.y(function(d,i){ return d.y*4; })
					.curve(interpolateTypes[p]);
	
	var shiftX = p*250;
	var shiftY = 0;
	
	var chartGroup = svg.append("g").attr("transform", "translate("+shiftX+",0)");

	chartGroup.append("path")
		  .attr("fill","none")
		  .attr("stroke","blue")
		  .attr("d",line(dataArray));
		  
	chartGroup.selectAll("circle.grp"+p)
		.data(dataArray)
		.enter().append("circle")
				.attr("class", function(d,i){ return "grp"+i; })
				.attr("cx",function(d,i){ return d.x*6; })
				.attr("cy",function(d,i){ return d.y*4; })
				.attr("r","2");
				
}

In the above example, we have created 6 charts with 6 dot indicating data points and each chart we have path added to it with different curve setting or interpolation methods.

  1. Create 1st line path and added 6 dots as the circle.
  2. Added all element with path and dot are group into 6 group element. As we can easily reposition group rather than reposition each individual element in the group.

We can see DOM structure of our above code.