block by dhoboy e61bf3bf8476b5b79adc

Cool pack layout mistake

Full Screen

This is an accident that occured while I was learning d3’s Pack Layout. I saved it becasue it looks really cool.

index.html

<html>
<head>
<script src="//d3js.org/d3.v3.js"></script>
</head>
<body>
<script>
// all these var will be visible inside d3.csv() 
var diameter = 960;
var format = d3.format(".2%");
var color = d3.scale.category20c();

/* the scales, add them to pack layout 
var xScale = d3.scale.linear()
					 .domain([0, dataset.length])
					 .range([w/4, (3*w)/4]);

var yScale = d3.scale.linear()
					 .domain([0, d3.max(dataset, function(d){ return d["pctOverObese"]; })])
					 .range([h - padding, padding]);	
		
var colorScale = d3.scale.linear()
						 .domain([0, d3.max(dataset, function(d){ return d["pctOverObese"]; })])
						 .range(["yellow", "red"]);
*/	

// set up pack layout	
var bubble = d3.layout.pack()
				    .sort(null)
				    .size([diameter, diameter])
				    .padding(1.5);

// append the svg
var svg = d3.select("body")
		    .append("svg")
		    .attr("height", diameter)
		    .attr("width", diameter)
		    .attr("class", "bubble");		

// pull in csv data
d3.csv("/d/283008a26997e97e0490/Student_Weight_Status_Category_Reporting_Results__Beginning_2010.csv", function(error, rows) {
	var dataset = [];
	rows.forEach(function(entry){
		if ((entry["GRADE LEVEL"] == "DISTRICT TOTAL") && (entry["PCT OVERWEIGHT OR OBESE"] != "")) {
			var pctOverObese = /[\d]+\.[\d]/.exec(entry["PCT OVERWEIGHT OR OBESE"]);
			if (pctOverObese != null) {
			  pctOverObese = pctOverObese[0] / 100; // form percent mathematically 
			  
			  // push data as an object ready for pack layout 
			  dataset.push({ name: entry["AREA NAME"], value: pctOverObese });
			}
		}
	});
	
  // set up scales
  var rScale = d3.scale.linear()
					 .domain([0, d3.max(dataset, function(d){ return d.value; })])
					 .range([2, 20]);

  // form csv as json
  var jsonData = { name: "overweightKids", children: dataset };
	
  console.log(jsonData)	
			  
  // create and draw nodes
  var node = svg.selectAll(".node")
			    .data(bubble.nodes(jsonData)
			      .filter(function(d) { return !d.children; }))
			    .enter()
			    .append("g")
			    .attr("class", "node")
			    .attr("transform", function(d) { 
			    		console.log(d);
			    		return "translate(" + d.x + "," + d.y + ")"; });

  node.append("title")
  	  .text(function(d){ return d.name + ": " + format(d.value); });
  
  node.append("circle")
  	  .attr("r", function(d) { return rScale(d.r); })
  	  .style("fill", function(d) { return color(d.name); });
  	  
  //node.append("text")
  	//  .attr("dy", ".3em")
  	  //.style("text-anchor", "middle")
  	  //.text(function(d) { return d.name.substring(0, d.r / 3); } );
	
}); // closes d3.csv()

d3.select(self.frameElement).style("height", diameter + "px");

</script>
</body>
</html>