Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Process multiple polygons d3

Tags:

d3.js

The answer below on drawing a polygon works well for a single polygon. However, what if there are more than one polygon? Simply adding an additional polygon with points seems not to work even though using "select all" would seem to indicate that it would be OK to add a couple more polygons without much problem..

We have an array of polygons, each of which has an attribute Points which is an array of points.

The first array with polygon should obviously be mapped and the point arrays of each member processed as described. But how to spedify this two-level structure with d3?

Proper format for drawing polygon data in D3

like image 528
user2083625 Avatar asked Jul 02 '26 01:07

user2083625


1 Answers

The answer is simple and straightaway. Just pass the array of polygons as data to d3 selection. In your case it seems that you are using an array of polygons which are composite objects, each having a key called 'Points'. I assume it looks something like this-

var arrayOfPolygons =  [{
    "name": "polygon 1",
    "points":[
      {"x":0.0, "y":25.0},
      {"x":8.5,"y":23.4},
      {"x":13.0,"y":21.0},
      {"x":19.0,"y":15.5}
    ]
  },
  {
    "name": "polygon 2",
    "points":[
      {"x":0.0, "y":50.0},
      {"x":15.5,"y":23.4},
      {"x":18.0,"y":30.0},
      {"x":20.0,"y":16.5}
    ]
  },
  ... etc.
];

You will just have to use d.Points instead of d when writing the equivalent map function, which can be written as follows-

vis.selectAll("polygon")
  .data(arrayOfPolygons)
  .enter().append("polygon")
  .attr("points",function(d) { 
    return d.points.map(function(d) { 
      return [scaleX(d.x),scale(d.y)].join(",");
    }).join(" ");
  })
  .attr("stroke","black")
  .attr("stroke-width",2);

You can check the following working JSFiddle to verify.

EDIT- The same example as above with convex hull implementation for rendering complete polygons. http://jsfiddle.net/arunkjn/EpBCH/1/ Note the difference in polygon#4

like image 171
arunkjn Avatar answered Jul 06 '26 07:07

arunkjn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!