D3 Scale Line Chart With Axis


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.bottom;
	//add svg with margin !important
	//this is svg is actually group
	var svg ="#diagram").append("svg")
				.append("g")  //add group to leave margin for axis
	//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
		if(a[0]< b[0]){
			return -1;
			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
	//add x and y axis
	var yAxis = d3.axisLeft(yScale);

	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")
      	.style("text-anchor", "middle")
	svg.append("text").text("X Label")
      	.style("text-anchor", "middle");


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