block by almccon 991e064a6680fed4726076d87406590c

USA 2012 presidential election (slow AF version)

Full Screen

Built with blockbuilder.org

forked from almccon‘s block: USA 2012 presidential election

index.html

<!DOCTYPE html>
<head>
  <meta charset="utf-8">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
  <script src="//d3js.org/topojson.v1.min.js"></script>
  <style>
    body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
    svg { width:100%; height: 100% }
  </style>
</head>

<body>
  <script>
    var width = 1000,
        height = 800;
    //var projection = d3.geo.albersUsa() // Did you know, it's actually the default projection for d3.geo.path?!
    //  .scale(500)
    //  .translate([width / 2, height / 2]);

    var color = d3.scale.linear()
        .domain([20,50,80])
        .range(['blue','purple','red']);

    var svg = d3.select("body").append("svg")

    var path = d3.geo.path();
    d3.json("elpo12p010g.topojson", function(error, usa2012) {
      if (error) return console.error(error);

      // Add the background
      svg.append("path")
        .datum(topojson.feature(usa2012, usa2012.objects.elpo12p010g))
        .attr("d", path)
        .style("fill", "#ddd");

      var counties = topojson.feature(usa2012, usa2012.objects.elpo12p010g).features;

      var barHeight = d3.scale.linear()
        .domain([0, d3.max(counties, function(d) { return +d.properties.TTL_VT; })])
        .range([0, 100]); // 0 to maximum height in pixels

      var circleRadius = d3.scale.sqrt()
        .domain([0, d3.max(counties, function(d) { return +d.properties.TTL_VT; })])
        .range([0, 50]); // 0 to maximum radius in pixels


      // add vertical bars for each county
      var countyBars = svg.append("g").attr("id", "countyBars");

      countyBars.selectAll("path")
          .data(counties.sort(function(a,b) { if (path.centroid(a)[1] < path.centroid(b)[1]) return 1; if (path.centroid(a)[1] > path.centroid(b)[1]) return -1; return 0; }))
        .enter().append("rect")
          .attr("x", function(d) { return path.centroid(d)[0] - 3; }) // Subtract 3 because width of bar will be 6
          .attr("y", function(d) { return path.centroid(d)[1] - barHeight(+d.properties.TTL_VT); })
          .attr("width", 6)
          .attr("height", function(d) { return  barHeight(+d.properties.TTL_VT); })
          .style("fill", function(d) { return color(+d.properties.PCT_ROM);});

      /*
      // add proportional circles for each county
      var countyCircles = svg.append("g").attr("id", "countyCircles");

      countyCircles.selectAll("path")
          .data(counties)
        .enter().append("circle")
          .attr("transform", function(d) { return "translate(" + path.centroid(d) + ")"; })
          .attr("r", function(d) { return circleRadius(+d.properties.TTL_VT); })
          .style("fill", function(d) { return color(+d.properties.PCT_ROM);});
      */
    });
  </script>
</body>