CODEXE

D3 Positive Negative Bar Chart


	var dataset = [4,2,-6,13,4,8,-23,19,10,-12,2,15];
	var maxHeight=d3.max(dataset,function(d){return d});
	var w = 500;
	var h = maxHeight*10*2+100;
	var svg = d3.select("body").append("svg").attr("width",w).attr("height",h);
	
	var barpadding = 2;
	var bars = svg.selectAll("rect").data(dataset).enter().append("rect");
	bars.attr("x",function(d,i){
			  return i*(w/dataset.length);
			  })
	.attr("y",function(d){
		if(d>0){
			return h/2-10*d;
		}
		else{
			return h/2
		}
	})//for bottom to top
	.attr("width", w/dataset.length-barpadding)
	.attr("height", function(d){
		return Math.abs(10*d);
	});
	bars.attr("fill",function(d){
		if(d<0){
			return "orange";
		}
		else{
			return "green";
		}
		//return "rgb(0,"+Math.abs(d*10)+",0)"
	});
	
	//add tag to every bar chart
	var tags = svg.selectAll("text").data(dataset).enter().append("text").text(function(d){
		return d;
	});
	tags.attr("x",function(d,i){
			  return i*(w/dataset.length)+13;
			  })
	.attr("y",function(d){
		if(d>0){
			return h/2-10*d+15;
		}
		else{
			return h/2+10*Math.abs(d)-5;
		}
	})//for bottom to top
	.attr("fill","white");