使用SVG从JSON文件绘制节点和链接

时间:2019-05-24 06:22:17

标签: javascript json d3.js svg

我是D3的新手,无法可视化json文件。我应该将位置(站点)绘制为半径等于“数量”的圆。我对如何使用节点和链接感到非常困惑。我还提供了JSON代码的示例。请帮助我了解我的编码哪里出问题了

 <html>
<head>
<title>D3 Visualisation </title>
<h1> Trading Data </h1>
 <style>
.svgCanvas {
border: solid 1px
}
        </style>
    </head>
    <body>
        <svg></svg>
<script src="https://d3js.org/d3.v4.min.js"></script> <script>
window.onload = function(){ 
    var width = 800;
    var height = 300;
    var thisCanvas = d3.select("svg")
    .attr("width", width)
    .attr("height", height)
    .attr("class", "svgCanvas");


d3.json("data.json", function(d){
    console.log(d);

var svgCanvas.selectAll("circle")
    .data(d).enter()
    .append("circle")
    .attr("cx", function(d) { return d.x; })
    .attr("cy", function(d) { return d.y; })
    .attr("r", function(d) { return d.amount; } )
    .style("fill", “lightgreen”); }) 


})
    }
        </script>
    </body>
</html>

Json代码示例如下:

{
  "nodes": [
    {
      "id": "site09",
      "x": 317.5,
      "y": 282.5
    },
    {
      "id": "site01",
      "x": 112,
      "y": 47
    },
    {
      "id": "site03",
      "x": 69.5,
      "y": 287
    }
  ],

  "links": [
    {"node01": "site05", "node02": "site08", "amount": 10},
    {"node01": "site05", "node02": "site02", "amount": 120},
    {"node01": "site05", "node02": "site03", "amount": 50}
  ]
}

1 个答案:

答案 0 :(得分:-1)

在这里您可以获得有效的解决方案。只需将数据对象替换为json。

https://playcode.io/324480?tabs=console&script.js&output

相关问题