如何使用数组(在 javascript 脚本中)创建带有 D3.js 的 SVG 多边形图表?

How to use an array (inside a javascript script) to create a SVG Polygon chart with D3.js?

我很头疼句法问题。我试过几个教程,none 有效。而且我不明白逻辑。请你还我微笑好吗? :D

我正在用 D3js 绘制多边形。

这非常有效=>

svg.append('polygon')
    .attr("points", "50,0, 89,19, 100,61, 72,94, 28,94")
    .attr("class", "radar-area");

但是这里我必须手动写点(不断移动...)

我将这些点收集在一个数组中,如下所示:

    var Data = [
        {"x":50,"y":0},
        {"x":89,"y":19},
        {"x":100,"y":61},
        {"x":72,"y":94},
        {"x":28,"y":94},
    ];

如何正确使用这个数组“数据”来设置多边形的点?

非常感谢您的帮助!

完整代码:

PHP 文件:

    <?php
    ob_start();
    require('view/resources/radar_chart.php');
    $radar_chart = ob_get_clean();
    ?>
/*and a bit further:*/
    <div class="radarchart"><?= $radar_chart ?></div>

JS脚本(所需资源):

<script src="//d3js.org/d3.v3.min.js"></script>
<script>
    var margin = {top:10, right:10, bottom:10, left:10},
            width = 120 - margin.left - margin.right,
            height = 120 - margin.top - margin.bottom;
    var svg = d3.select('.radarchart')
        .append('svg');
    svg.attr('width', width + margin.left + margin.right);
    svg.attr('height', height + margin.top + margin.bottom);

    var Data = [
        {"x":50,"y":0},
        {"x":89,"y":19},
        {"x":100,"y":61},
        {"x":72,"y":94},
        {"x":28,"y":94},
    ];
    /*In fact, this array is filled by variables, but useless to complexify with that here, so I replaced with figures*/

svg.append('polygon')
    .attr("points", ""/*How do I get the points from "Data" ?*/)
    .attr("class", "radar-area");

</script>

以及 CSS 文件中的 class“雷达区域”:

.radar-area{
    fill: var(--theme-pink);
}

小改动,因为您可以使用 ES 解构

另请注意 空格 (或混合)都可以用作分隔符

var Data = [
        {"x":50,"y":0},
        {"x":89,"y":19},
        {"x":100,"y":61},
        {"x":72,"y":94},
        {"x":28,"y":94},
    ];
var points = Data.map(({x,y}) => x+","+y).join(",");

document.body.append(points)