d3.js

tree layout, tree.nodes, tree.links

Naranjito 2020. 12. 29. 18:31

Let's make tree layout with external json file.

 

 

  • JSON file
{
    "name": "max",
    "children": [{
      "name": "Sylvia",
      "children": [{
        "name": "Craig"
       },
       {
        "name": "Robin"
       },
       {
        "name": "Anna"
       }
      ]
     },
     {
      "name": "David",
      "children": [{
        "name": "Jeff",
        "size": 3534
       },
       {
        "name": "Buffy",
        "size": 5731
       }
      ]
     }
    ]
   }

 

Let's make tree layout with this guys.

 

 

  • HTML document
<!DOCTYPE html>
<html lang="en">
<head>
    
    <title>D3js</title>
    <script src="https://d3js.org/d3.v3.min.js"></script>

</head>
<body>

    

    <script>


        var canvas = d3.select("body").append("svg")
            .attr("width",500)
            .attr("height",500)
            .append("g")
                .attr("transform","translate(50,50)");
        

        var tree = d3.layout.tree()
            .size([400,400]) 
            
        d3.json("mydata.json",function (data) {
            var nodes = tree.nodes(data); //it returns all the objects in the json file in other words, it returns an array of all the nodes
            var links = tree.links(nodes);//path between each node

            var node = canvas.selectAll(".node")
                .data(nodes)
                .enter()
                .append("g")
                    .attr("class","node")
                    .attr("transform",function (d) {return "translate("+d.y + ","+d.x+")";})

            node.append("circle")
                .attr("r",5)
                .attr("fill","skyblue");

            node.append("text")
                .text(function (d) {return d.name;});


            var diagonal = d3.svg.diagonal()
                .projection(function (d) {return [d.y, d.x];}); //path generator which is converts the start and ending points of each object

            canvas.selectAll(".link")
                .data(links)
                .enter()
                .append("path")
                .attr("class", "link") //it gives each path the class of link
                .attr("fill","none")
                .attr("stroke","#ADADAD")
                .attr("d", diagonal);
        })
    </script>
    
</body>
</html> 

 

 

  • Result

'd3.js' 카테고리의 다른 글

histogram layout, parseInt  (0) 2020.12.30
cluster  (0) 2020.12.30
diagonal  (0) 2020.12.29
scaleOrdinal, pie, centroid  (0) 2020.12.29
arc  (0) 2020.12.29