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

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

d3

File size: 2.2 KB
Line 
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    .attr("width", 960 + 100)
20    .attr("height", 500 + 100)
21  .append("svg:g")
22    .attr("transform", "translate(50,50)");
23
24d3.json("../data/us-state-centroids.json", function(states) {
25  var project = d3.geo.albersUsa(),
26      idToNode = {},
27      links = [],
28      nodes = states.features.map(function(d) {
29    var xy = project(d.geometry.coordinates);
30    return idToNode[d.id] = {
31      x: xy[0],
32      y: xy[1],
33      gravity: {x: xy[0], y: xy[1]},
34      r: Math.sqrt(data[+d.id] * 5000),
35      value: data[+d.id]
36    };
37  });
38
39  force
40      .nodes(nodes)
41      .links(links)
42      .start()
43      .on("tick", function(e) {
44    var k = e.alpha,
45        kg = k * .02;
46    nodes.forEach(function(a, i) {
47      // Apply gravity forces.
48      a.x += (a.gravity.x - a.x) * kg;
49      a.y += (a.gravity.y - a.y) * kg;
50      nodes.slice(i + 1).forEach(function(b) {
51        // Check for collisions.
52        var dx = a.x - b.x,
53            dy = a.y - b.y,
54            l = Math.sqrt(dx * dx + dy * dy),
55            d = a.r + b.r;
56        if (l < d) {
57          l = (l - d) / l * k;
58          dx *= l;
59          dy *= l;
60          a.x -= dx;
61          a.y -= dy;
62          b.x += dx;
63          b.y += dy;
64        }
65      });
66    });
67
68    svg.selectAll("circle")
69        .attr("cx", function(d) { return d.x; })
70        .attr("cy", function(d) { return d.y; });
71  });
72
73  svg.selectAll("circle")
74      .data(nodes)
75    .enter().append("svg:circle")
76      .style("fill", function(d) { return color(d.value); })
77      .attr("cx", function(d) { return d.x; })
78      .attr("cy", function(d) { return d.y; })
79      .attr("r", function(d, i) { return d.r; });
80});
Note: See TracBrowser for help on using the repository browser.