CODEXE

D3 Scale 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 Math.abs(d);
			}); 
	var minHeight=d3.min(dataset, function(d){
				if(d>=0)
					return d;
			});
	var w = 500;
	var h = 200;//maxHeight*10*2+100;
	var hScale = d3.scaleLinear()
				.domain([0, maxHeight])
				.range([0,h/2]);
	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-hScale(d);
		}
		else{
			return h/2;
		}
	})//for bottom to top
	.attr("width", w/dataset.length-barpadding)
	.attr("height", function(d){
		return hScale(Math.abs(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-hScale(d)+15;
		}
		else{
			return h/2+hScale(Math.abs(d))-5;
		}
	})//for bottom to top
	.attr("fill","white");