d3.js

histogram layout, parseInt

Naranjito 2020. 12. 30. 18:48

Let's make histogram layout with external csv file.

 

 

  • CSV file
"name","age"
"maria",30
"fred",10
"franci",40
"mari",35
"fre",56
"franc",60
"ma",70
"fr",37
"fran",19

 

Let's make histogram 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>

        d3.csv("mydata.csv", function (data){ //data is stored in this data
            var map = data.map(function (i) {return parseInt(i.age);}) //map goes through each element in array and returns a new array based on criteria
            //convert string to the numbers with parseInt

            var histogram = d3.layout.histogram()
                .bins(7)
                (map)
            
            var canvas = d3.select("body").append("svg")
                .attr("width", 500)
                .attr("height", 500);

            var bars = canvas.selectAll(".bar")
                .data(histogram)
                .enter()
                .append("g") //it will append a rectangle which is the actual bar
            
            bars.append("rect")
                .attr("x", function (d) {return d.x*5;}) //lower bound of each bin or interval
                .attr("y", 0)
                .attr("width", function (d) {return d.dx*5-5;}) //represents the range or span of each bin since they are all uniformly they have the same range
                .attr("height", function (d) {return d.y*20;})
                .attr("fill","orange")
                ;


        });


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

 

  • Result

 

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

treemap, category10, children, text-anchor  (0) 2020.12.31
histogram, linear, axis, map  (0) 2020.12.31
cluster  (0) 2020.12.30
tree layout, tree.nodes, tree.links  (0) 2020.12.29
diagonal  (0) 2020.12.29