d3.js

scaleOrdinal, pie, centroid

Naranjito 2020. 12. 29. 15:19

Following the previous post(2020/12/29 - [d3.js] - arc), let's apply the color and complete pie layout.

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

</head>
<body>

    

    <script>


        var data = [10, 50, 80];

        var canvas = d3.select("body").append("svg")
            .attr("width",1500)
            .attr("height",1500);
        
        var r = 300;
       
        var color = d3.scaleOrdinal() //input is not quantitative it can consist of a number of names or anything that is not a continuous domain
            .range(["red","blue","orange"])

        var group = canvas.append("g")
            .attr("transform", "translate(300,300)");
        
        var arc = d3.arc()
            .innerRadius(200)
            .outerRadius(r); //startAngle and endAngle will be provided by pie layout

        var pie = d3.pie()
            .value(function (d) {return d;});  //need to specify how this layout is to fetch the data

        var arcs = group.selectAll(".arc") //select everything that has the class
            .data(pie(data)) //pass the data to pie layout
            .enter()
            .append("g")
            .attr("class", "arc"); //every group element has the class of arc

        arcs.append("path")  
            .attr("d",arc)
            .attr("fill",function (d){return color(d.data);});

        arcs.append("text")
            .attr("transform", function (d) {return "translate("+arc.centroid(d)+")";})//put the labels at the right place
            .attr("text-anchor","middle")
            .attr("font-size","1.5em")
            .text(function (d){return d.data;});
    </script>
    
</body>
</html> 

 

 

  • Result

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

tree layout, tree.nodes, tree.links  (0) 2020.12.29
diagonal  (0) 2020.12.29
arc  (0) 2020.12.29
path  (0) 2020.12.29
load external data(json data)  (0) 2020.12.28