I have an array of objects.These objects contain a set of attributes named "x" and "y". Now as i iterate through the array,i append circle for each object into array taking these coordinates as center of the circle. Now,instead of appending the circle for each and every data point,I want to append randomly selected polygon like star/pentagon/hexagon/circle etc. How to do this in d3? (PS:I am stuck at the logic of choosing and appending polygons randomly and how to choose points for drawing the polygon using the coordinates of traversed object in Array)
My current code is:
var data=[
{"x":"100","y":"20","index":"1"},
{"x":"150","y":"22","index":"2"},
{"x":"200","y":"100","index":"3"},
{"x":"210","y":"40","index":"4"},
{"x":"300","y":"30","index":"5"}
];
var svgHeight=800;
var svgWidth=800;
var margin=50;
var divelement=d3.select("body")
.append("div")
.attr("height",svgHeight)
.attr("width",svgWidth)
.attr("style","border:1px solid black;");
var svgElement=divelement.append("svg")
.attr("height",svgHeight)
.attr("width",svgWidth);
var boxGroupElement=svgElement.append("g")
.attr("transform","translate("+margin+","+margin+")");
boxGroupElement.selectAll("path")
.data(data)
.enter()
.append("path")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
.attr("d", d3.svg.symbol().size(200).type(function(d){
return d.index%6;
}))
.attr("fill","yellow")
.attr("stroke","blue");
I know it's not exactly super beautiful, but you could use d3.svg.symbol():
boxGroupElement.append("path")
.attr("transform", function(d) { return "translate("
+ data[a].x + "," + data[a].y + ")"; })
.attr("d", d3.svg.symbol().size(200).type(d3.svg.symbolTypes[~~(Math.random()
* d3.svg.symbolTypes.length)]))
.attr("fill","yellow")
.attr("stroke","blue");
Here is the fiddle: https://jsfiddle.net/gerardofurtado/sk1jqary/1/ . I took the liberty of changing your data just to separate the symbols a little bit.
As I used a random number for the symbol, every time you click "run", a new set of symbols will appear.
This is the API: https://github.com/d3/d3/wiki/SVG-Shapes#symbol. The symbols are:
As I said, not very beautiful... but you can create your own polygons and append them, using polygon: https://github.com/d3/d3/wiki/SVG-Shapes#svg_polygon
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With