Proper format for drawing polygon data in D3

前端 未结 3 1752
长情又很酷
长情又很酷 2020-12-09 04:33

I\'ve tried this different ways, but nothing seems to be working. Here is what I currently have:

var vis = d3.select(\"#chart\").append(\"svg\")
         .at         


        
相关标签:
3条回答
  • 2020-12-09 05:07

    are you trying to draw polygon shapes? - like this. http://bl.ocks.org/2271944 The start of your code looks like a typical chart - which would usually conclude something like this.

    chart.selectAll("line")
         .data(x.ticks(10))
       .enter().append("line")
         .attr("x1", x)
         .attr("x2", x)
         .attr("y1", 0)
         .attr("y2", 120)
    .style("stroke", "#ccc");
    
    0 讨论(0)
  • 2020-12-09 05:15

    A polygon looks something like: <polygon points="200,10 250,190 160,210" />

    So, your full poly array should produce one long string that will create one polygon. Because we are talking about one polygon the data join should also be an array with only one element. That is why the code below shows: data([poly]) if you wanted two identical polygons you would change this to data([poly, poly]).

    The goal is to create one string from your array with 4 objects. I used a map and another join for this:

    poly = [{"x":0.0, "y":25.0},
            {"x":8.5,"y":23.4},
            {"x":13.0,"y":21.0},
            {"x":19.0,"y":15.5}];
    
    vis.selectAll("polygon")
        .data([poly])
      .enter().append("polygon")
        .attr("points",function(d) { 
            return d.map(function(d) {
                return [scaleX(d.x),scaleY(d.y)].join(",");
            }).join(" ");
        })
        .attr("stroke","black")
        .attr("stroke-width",2);
    

    See working fiddle: http://jsfiddle.net/4xXQT/

    0 讨论(0)
  • 2020-12-09 05:23

    The above answers are needlessly complicated.

    All you have to do is specify the points as a string and everything works fine. Something like this below will work.

    var canvas = d3.select("body")
       .append("svg")
       .attr("height", 600)
       .attr("width", 600);
    
    canvas.append("polygon")
       .attr("points", "200,10 250,190 160,210")
       .style("fill", "green")
       .style("stroke", "black")
       .style("strokeWidth", "10px");
    
    0 讨论(0)
提交回复
热议问题