whistler
whistler

Reputation: 886

d3 drawing polygons from a csv

My data looks like the following and is contained in a csv file:

x,y,id
95,100,1
89,92,1
72,107,1
68,114,1
67,121,1
126,41,2
124,43,2
124,46,2
126,47,2
…

Each id identifies a polygon to plot and the x,y columns are the locations of the points or vertices of the respective polygon. I have done basic plots thus far, where the data has been organized in a way that was not complicated. For this case, after doing some reading, I thought I would need to use the nest function to group the data by id (so that all data for each polygon are grouped together):

var dataset=d3.nest()
    .key(function(d) {return d.id;})
    .sortKeys(d3.ascending)
    .entries(dataset);

After doing so, I am trying something along the lines of:

var g = d3.select("svg").selectAll("g").data(dataset).enter()
    .append("g")
    .append("polygon")
    .attr("points",function(d) {return ?})
    .style("fill", "brown");

But I'm not sure a) how to specify the points attribute value in the proper String format and b) if this is the correct way to draw each polygon from the file? Any help would be greatly appreciated.

Upvotes: 1

Views: 1364

Answers (2)

Christopher Hackett
Christopher Hackett

Reputation: 6192

Lars' suggestion is correct but you may also wish to consider the inexplicit dependency you may not have noticed. The draw polygon is dependent on the order in which the entries are found in your original CSV file. For example for 1 two of the possible permutations could be.

enter image description here

You probably want to acknowledge this dependency explicit even if it currently is working fine for you by including the row number in each datum or some other action which is relevant for your data then ensure you order the data when accessing the points information.

Upvotes: 2

Lars Kotthoff
Lars Kotthoff

Reputation: 109292

Your approach seems right to me, you just need to extract the point coordinates now. For this, you need to iterate of the values of each key and for each, get x and y.

var g = d3.select("svg").selectAll("g").data(dataset).enter()
  .append("g")
  .append("polygon")
  .attr("points",function(d) {
    return d.values.map(function(e) { return e.x + "," + e.y; }).join(" ");
  })
  .style("fill", "brown");

Upvotes: 1

Related Questions