user2391236
user2391236

Reputation:

How to create more than one d3 polygon

I have edited this question a little bit from when I posted it. Here is the new code: Here is my code:

        var elementTags = ["Google", 4, "Wikipedia", "Yahoo!", "Cindy"];
        var _s32 = (Math.sqrt(3)/2);
        var A = 75;
        var _counter = 0;
        var xDiff;
        var yDiff;
        var pointData = [[A+xDiff, 0+yDiff], [A/2+xDiff, (A*_s32)+yDiff], [-A/2+xDiff, (A*_s32)+yDiff], [-A+xDiff, 0+yDiff],
        [-A/2+xDiff, -(A*_s32)+yDiff], [A/2+xDiff, -(A*_s32)+yDiff], [A+xDiff, 0+yDiff]];
        var svgContainer = d3.select("body") //create container
                .append("svg")
                .attr("width", 1000)
                .attr("height", 1000);

        var enterElements = svgContainer.selectAll("path.area") //draw elements
                .data([pointData]).enter().append("path")
                .style("fill", "#ff0000")
                .attr("d", d3.svg.area());

What I want to do is create a new hexagon for each elementTags value. Each new hexagon should have a randomized xDiff and yDiff, and each time the value of _counter should go up by 1.

Upvotes: 0

Views: 535

Answers (2)

Steve P
Steve P

Reputation: 19377

I had a similar situation, described in this question. I put together a code example which you can find here: http://bl.ocks.org/explunit/4659227

The key idea is that the path-generating function can be called during the append of each data point:

svg.selectAll("path")
  .data(nodes).enter().append("svg:path")
  .attr("d", function(d) { return flow_shapes[d.NodeType](d.height, d.width);})

It's hard to tell from your code but it appears maybe you are trying to call .append in a loop rather than building your data and then letting D3 add all the notes in a single statement.

It might be helpful for you to put your complete code in a JSFiddle so we can see all of what you're trying.

Upvotes: 0

terales
terales

Reputation: 3200

You need to use loop. Here is a modified code:

var elementTags = ["Google", 4, "Wikipedia", "Yahoo!", "Cindy"];
var _s32 = (Math.sqrt(3)/2);
var A = 75;

var svgContainer = d3.select("body") //create container
        .append("svg")
        .attr("width", 1000)
        .attr("height", 1000);

for (index = 0; index < elementTags.length; index++) {
    var xDiff = Math.random()*100+100;
    var yDiff = Math.random()*100+100;
    var pointData = [
        [A+xDiff, 0+yDiff]
        , [A/2+xDiff, (A*_s32)+yDiff]
        , [-A/2+xDiff, (A*_s32)+yDiff]
        , [-A+xDiff, 0+yDiff]
        , [-A/2+xDiff, -(A*_s32)+yDiff]
        , [A/2+xDiff, -(A*_s32)+yDiff]
        , [A+xDiff, 0+yDiff]
    ];

    var enterElements = svgContainer.selectAll("path.area") //draw element
        .data([pointData]).enter().append("path")
        .style("fill", "#ff0000")
        .attr("d", d3.svg.area());
}

Is it doing what you want?

Upvotes: 1

Related Questions