Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For some reason, my D3 Map is displaying upside down - how can I flip it?

Have a topoJSON file that I am importing - seems like this should be easy to flip, but I have no idea. Should I be transforming the object after it's created or adjusting the JSON? I tried using some projections, which flipped the object, but distorted it all over the place.

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

.counties {
  fill: blue;
}

.states {
  fill: none;
  stroke: #fff;
  stroke-linejoin: round;
}

</style>
<svg width="960" height="600"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>
<script src="https://d3js.org/topojson.v2.min.js"></script>
<script>


var svg = d3.select("svg"),
    width = +svg.attr("width"),
    height = +svg.attr("height");

var path = d3.geoPath()

 //first make projection  
  //var projection = d3.geoMercator();
  //var path = d3.geoPath()
  //  .projection(projection);



d3.json("data.topojson", function(error, us) {
  if (error) throw error;


 var counties = topojson.feature(us, us.objects.counties),
                    counties = counties.features.filter(function(d) { return d.properties.AWATER === 0; });

  svg.append("g")
      .attr("class", "counties")
    .selectAll("path")
      .data(counties)
    .enter().append("path")
      .attr("d", path)
      .style("fill", 'blue')
      .append('g')
      attr('transform', 'rotate(180 0 0)');
});

</script>
like image 971
Browning Gentry Avatar asked Mar 07 '23 22:03

Browning Gentry


1 Answers

You aren't using a projection - so the coordinates in the file are translated to pixels with no transformation. If your data has typical geographic coordinates, or lat longs that are both positive, high values are at the north end (the top in most maps), and low values are at the south end (the bottom in most maps).

In svg coordinates, low values are located at the top and increase as one moves towards the bottom - the opposite of most geographic coordinate conventions. You could use a geoIdentity as your projection to flip the json's y coordinates:

var projection = d3.geoIdentity()
  .reflectY(true)
  .fitSize([width,height],geojson)

Where geojson is your feature collection: topojson.feature(us, us.objects.counties)

And then use it with your path:

var path = d3.geoPath().projection(projection);
like image 151
Andrew Reid Avatar answered Apr 07 '23 17:04

Andrew Reid