block by mpmckenna8 055dac2afb730a855898

d3 topo color by neighbor CA Assembly Districts

Full Screen

So if you have a bunch of polygons and they’re topojson and you want to show em using d3 there’s a handy dandy neighbors method which when combined with a color scale generator makes coloring polygons a breeze.

You still need to be careful though, I’m using 8 or maybe 9 colors, I still haven’t really figured out how it’s working. But at least I got it to work. Now read the docs and see if I can wrap my head around the colors and scales stuff.

https://github.com/mbostock/d3/wiki

index.html

<!DOCTYPE html>
<meta charset="utf-8">
    <style>

        /* CSS goes here. */
        .casubun {
          //  fill: #003831;
        }

        .bords{
          fill:none;
          stroke-width:2px;
          stroke:white;
        }


        </style>
    <body>

        <script src="//d3js.org/d3.v3.min.js"></script>
<script src="//d3js.org/topojson.v1.min.js"></script>


        <script>

            /* JavaScript goes here. */
  //choose dimensions of my svg thing
      var width = 960,
      height = 600;
var color = d3.scale.category10();
    color.range(color.range().slice(0,8));

//Choosing mercator because that's what I made the data in and also scale and center setting
      var projection = d3.geo.mercator()
        .scale(2000)
        .translate([width / 2, height / 2])
        .center([-120,36])
      ;

// So now when I call path on jam it will use this projection and stuff
      var path = d3.geo.path()
        .projection(projection);

// Appending the actual SVG to the body of the page w/ height width
      var svg = d3.select("body").append("svg")
        .attr("width", width)
        .attr("height", height);



      d3.json("/mpmckenna8/raw/60910c22b47777967704/calAss1.json", function(cali) {
        var neighbors = topojson.neighbors(cali.objects.assemD2011.geometries);
        var districts = topojson.feature(cali, cali.objects.assemD2011).features;

        svg.selectAll(".casubun")
        .data(districts)
        .enter().append("path")
        .attr("class", function(d) { return "casubun"; })
        .attr("d", path)
        .style("fill",function(d,i){
          return color(d.color=d3.max(neighbors[i],function(n){
            return districts[n].color;
          })
        + 1 | 0
      );
        })
        ;

      svg.append("path")
        .datum(topojson.mesh(cali,cali.objects.assemD2011, function(a,b){

          return a;
        }))
        .attr("d",path)
        .attr("class", "bords");

              });


      d3.select("body")
       .transition()
       .style("background-color", "black");



            </script>
    </body>