CODEXE

D3 Scale Line Chart With Axis

Note:

Line vary smoothly -- Basis

Line has sharp -- Other features

Reason:Stack Overflow


	.line {
	  fill: none;
	  stroke: steelblue;
	  stroke-width: 2px;
	}
            	

	var margin = {top: 20, right: 20, bottom: 50, left: 70};
    var width = 500 - margin.left - margin.right;
    var height = 200 - margin.top - margin.bottom;
	
	//add svg with margin !important
	//this is svg is actually group
	var svg = d3.select("#diagram").append("svg")
				.attr("width",width+margin.left+margin.right)
				.attr("height",height+margin.top+margin.bottom)
				.append("g")  //add group to leave margin for axis
				.attr("transform","translate("+margin.left+","+margin.top+")");
	
	
	//the code above should be same
	
	var dataset = [[5, 20], [480, 90], [250, 50], [100, 33], [330, 95],
                [410, 12], [475, 44], [25, 67], [85, 21], [220, 88]];
	//for each d, d[0] is the first num, d[1] is the second num
	//set y scale
	var yScale = d3.scaleLinear().rangeRound([0,height]).domain([d3.max(dataset,function(d){return d[1];}),d3.min(dataset,function(d){return d[1];})]);//show negative
	//add x axis
	var xScale = d3.scaleLinear().rangeRound([0,width]).domain(d3.extent(dataset, function(d){return d[0];}));//scaleBand is used for  bar chart
	
	//sort x
	dataset.sort(function(a,b){
		if(a[0]< b[0]){
			return -1;
		}
		else{
			return 1;
		}
	})
	
	var line = d3.line()
		.x(function(d){return xScale(d[0]);})
		.y(function(d){return yScale(d[1]);})
		.curve(d3.curveBasis);//default is d3.curveLinear
	
	//add line to svg. use path-- > to know svg path
	//must add css class line, you can try to remove it and see the result
	svg.append("path").data([dataset]).attr("class","line").attr("d",line);
	
	//add x and y axis
	var yAxis = d3.axisLeft(yScale);
	svg.append("g").call(yAxis);
	

	var xAxis = d3.axisBottom(xScale);/*.tickFormat("");remove tick label*/
	svg.append("g").call(xAxis).attr("transform", "translate(0,"+height+")");
	
	//add label for x axis and y axis
	svg.append("text").text("Y Label")
		.attr("x",0-height/2)
		.attr("y",0-margin.left)
		.attr("dy","1em")
      	.style("text-anchor", "middle")
		.attr("transform","rotate(-90)");
	svg.append("text").text("X Label")
		.attr("x",width/2)
		.attr("y",height+margin.bottom)
      	.style("text-anchor", "middle");
            	

Tips:

Use basis may lose precision in the chart!

The basis interpolation is implementing a beta spline, which people like to use as an interpolation function precisely because it smooths out extreme peaks. This is useful when you are modeling something you expect to vary smoothly but only have sharp, infrequently sampled data. A consequence of this is that resulting line will not connect all data points, changing the appearance of extreme values.

Source:Stack Overflow