d3.js

treemap, category10, children, text-anchor

Naranjito 2020. 12. 31. 17:42

Let's create treemap with same json file as previous post(2020/12/29 - [d3.js] - tree layout, tree.nodes, tree.links), (

2020/12/30 - [d3.js] - cluster).

 

  • 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 color = d3.scale.category10(); //it provides a scale of 10 colors 

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

        d3.json("mydata.json",function (data) {
            var treemap = d3.layout.treemap()
                .size([500,500]) //same size as the canvas
                .nodes(data) //nodes where he data is coming from

            var cells = canvas.selectAll(".cell")//bind the data to the document and g element for each of the notes
                .data(treemap)
                .enter()
                .append("g")
                .attr("class", "cell")

            cells.append("rect")
                .attr("x",function (d) {return d.x;})
                .attr("y",function (d) {return d.y;})
                .attr("width",function (d) {return d.dx;})
                .attr("height",function (d) {return d.dy;})
                .attr("fill", function (d) {return d.children ? null : color(d.parent.name);}) //defining the color based on the parent of each object,
                //but all object doesnt have parents so if it has children, return null so no color
                //else return parents name
                .attr("stroke", "#fff") //separate the rectangles within each group

            cells.append("text")
                .attr("x", function(d) {return d.x+d.dx/2})//d.x is left border, add the extent of that data so it will be to the text will be positioned to right
                //then divide this by 2 so it is displayed in the middle of each rectangle
                .attr("y", function (d) {return d.y+d.dy/2} )
                .attr("text-anchor","middle") //adjust the labels which are a little bit to the right to the middle 
                .text(function (d) {return d.children ? null : d.name;})// only want to return the names of the leaf nodes so if there is childen, return null else return the name 
        })


    </script>
</body>
</html>

 

 

  • Result

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

D3, DOM, select, selectAll, .data, .enter, .append, .text, .exit  (0) 2021.01.04
maps, geoMercator, geoPath, projection  (0) 2020.12.31
histogram, linear, axis, map  (0) 2020.12.31
histogram layout, parseInt  (0) 2020.12.30
cluster  (0) 2020.12.30