Process multiple polygons d3

The answer to a polygon pattern works well for a single polygon. However, if there is more than one polygon? Just adding an additional polygon with points seems to be inoperative, although using "select all" would show that it would be nice to add a few more polygons without any problems.

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

The first array with the polygon obviously needs to be matched, and the point arrays of each element are processed as described. But how to execute this two-level structure with d3?

The right format for drawing polygonal data in D3

+4
source share
1 answer

The answer is simple and immediate. Just pass an array of polygons as data to select d3. In your case, it seems that you are using an array of polygons, which are composite objects, each of which has 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 need 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(dx),scale(dy)].join(","); }).join(" "); }) .attr("stroke","black") .attr("stroke-width",2); 

You can check the following working JSFiddle for confirmation.

EDIT - Same example as above, with a convex hull for rendering full polygons. http://jsfiddle.net/arunkjn/EpBCH/1/ Note the difference in polygon # 4

+1
source

All Articles