CODEXE

D3 Brush Bar Chart


              var margin = {top: 20, right: 20, bottom: 50, left: 70};
    	var width = 500 - margin.left - margin.right;
		var height = 200 - margin.top - margin.bottom;
		
		var svg = d3.select("#diagram").append("svg")
					.attr("width", width+margin.left+margin.right)
					.attr("height", height+margin.top+margin.bottom)
					.append("g")
					.attr("transform","translate("+margin.left+","+margin.right+")");
		var dataset = [4,2,6,13,4,8,32,19,10,12,2,15];
		var maxHeight=d3.max(dataset,function(d){return d});
		var minHeight=d3.min(dataset,function(d){return d})

		//set y scale
		var yScale = d3.scaleLinear().range([0,height]).domain([maxHeight,0]);
		//add x axis
		var xScale = d3.scaleBand().rangeRound([0,width]).padding(0.1);//scaleBand is used for  bar chart
		xScale.domain([0,1,2,3,4,5,6,7,8,9,10,11]);//value in this array must be unique
		/*if domain is specified, sets the domain to the specified array of values. The first element in domain will be mapped to the first band, the second domain value to the second band, and so on. Domain values are stored internally in a map from stringified value to index; the resulting index is then used to determine the band. Thus, a band scale’s values must be coercible to a string, and the stringified version of the domain value uniquely identifies the corresponding band. If domain is not specified, this method returns the current domain.*/

		var bars = svg.selectAll("rect").data(dataset).enter().append("rect");
		bars.attr("x",function(d,i){
				  return xScale(i);//i*(width/dataset.length);
				  })
		.attr("y",function(d){
			return yScale(d);
		})//for bottom to top
		.attr("width", xScale.bandwidth()/*width/dataset.length-barpadding*/)
		.attr("height", function(d){
			return height-yScale(d);
		});
		bars.attr("fill","steelblue");

		svg.append("g")
			.attr("transform","translate(0,"+height+")")
			.call(d3.axisBottom(xScale));
	
		svg.append("g")
			.call(d3.axisLeft(yScale));
			//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")
		
		//add brush
		var brush = d3.brushX()
					.extent([[0,0],[width,height]])//(x0,y0)  (x1,y1)
					.on("end",brushend);//when mouse up, move the selection to the exact tick //start(mouse down), brush(mouse move), end(mouse up)
		svg.append("g")
			.attr("class","brush")
			.call(brush);
		
		function brushend(){
			if (!d3.event.sourceEvent) return; // Only transition after input.
  			if (!d3.event.selection) return; // Ignore empty selections.
			console.log(d3.event.selection);
			var areaArray = d3.event.selection;//[x0,x1]
			
		}