source: Dev/trunk/d3/examples/cartogram/demers.js @ 76

Last change on this file since 76 was 76, checked in by fpvanagthoven, 14 years ago

d3

File size: 2.2 KB
RevLine 
[76]1// Ratio of Obese (BMI >= 30) in U.S. Adults, CDC 2008
2var data = [
3  , .187, .198, , .133, .175, .151, , .1, .125, .171, , .172, .133, , .108,
4  .142, .167, .201, .175, .159, .169, .177, .141, .163, .117, .182, .153, .195,
5  .189, .134, .163, .133, .151, .145, .13, .139, .169, .164, .175, .135, .152,
6  .169, , .132, .167, .139, .184, .159, .14, .146, .157, , .139, .183, .16, .143
7];
8
9var color = d3.scale.linear()
10    .domain([d3.min(data), d3.max(data)])
11    .range(["#aad", "#556"]);
12
13var force = d3.layout.force()
14    .charge(0)
15    .gravity(0)
16    .size([960, 500]);
17
18var svg = d3.select("#chart").append("svg:svg");
19
20d3.json("../data/us-state-centroids.json", function(states) {
21  var project = d3.geo.albersUsa(),
22      idToNode = {},
23      links = [],
24      nodes = states.features.map(function(d) {
25    var xy = project(d.geometry.coordinates);
26    return idToNode[d.id] = {
27      x: xy[0],
28      y: xy[1],
29      gravity: {x: xy[0], y: xy[1]},
30      r: Math.sqrt(data[+d.id] * 2500),
31      value: data[+d.id]
32    };
33  });
34
35  force
36      .nodes(nodes)
37      .links(links)
38      .start()
39      .on("tick", function(e) {
40    var k = e.alpha * .5,
41        kg = k * .1;
42    nodes.forEach(function(a, i) {
43      // Apply gravity forces.
44      a.x += (a.gravity.x - a.x) * kg;
45      a.y += (a.gravity.y - a.y) * kg;
46      nodes.slice(i + 1).forEach(function(b) {
47        // Check for collision
48        var dx = a.x - b.x,
49            dy = a.y - b.y,
50            d = a.r + b.r,
51            lx = Math.abs(dx),
52            ly = Math.abs(dy);
53        if (lx < d && ly < d) {
54          lx = (lx - d) / lx * k;
55          ly = (ly - d) / ly * k;
56          dx *= lx;
57          dy *= ly;
58          a.x -= dx;
59          a.y -= dy;
60          b.x += dx;
61          b.y += dy;
62        }
63      });
64    });
65
66    svg.selectAll("rect")
67        .attr("x", function(d) { return d.x - d.r; })
68        .attr("y", function(d) { return d.y - d.r; });
69  });
70
71  svg.selectAll("rect")
72      .data(nodes)
73    .enter().append("svg:rect")
74      .style("fill", function(d) { return color(d.value); })
75      .attr("x", function(d) { return d.x - d.r; })
76      .attr("y", function(d) { return d.y - d.r; })
77      .attr("width", function(d) { return d.r * 2; })
78      .attr("height", function(d) { return d.r * 2; });
79});
Note: See TracBrowser for help on using the repository browser.