The use of scale in D3.js

1. Why use scale
Map an area to another area with the same size relationship
2. What scales are there

The scale in D3 is very similar to the function in mathematics
 Given an x (definition field). It also determines a y (value range).
D3 is called domain and range.
When we use it, we need to give the scope of domain and range to get a mapping relationship
  • Linear Billy rule

    Mapping a continuous interval to another interval
    Suppose you have the following array
    var dataset = [1.2, 2.3, 0.9, 1.5, 3.3];
    Requirement: map the minimum to 0 and the maximum to 300

var min=d3.min(dataset);
var max=d3.max(dataset);
var linear=d3.scale.linear()
    .domain([min,max])
    .range([0,300])
console.log(linear(0.9))   //0
console.log(linear(3.3))   //300

The return value of d3.scale.linear() can be used as a function. Therefore, there is such a usage: linear(0.9).

  • Ordinal scale
    Sometimes domain and range are not continuous
    For example:
var index=[0,1,2,3,4];
var color=["red","blue","green","yellow","black"]

We want 0 to correspond to red, 1 to correspond to blue, and so on
In this case, the ordinal scale is needed

var ordinal=d3.scale.ordinal()
        .domain(index)
        .range(color);

ordinal(0)  //red
ordinal(4)  //black

3. Add scale to column chart

    <html>

<head>
    <meta charset="utf-8">
    <title>hello world</title>
</head>

<body>
    <p>Apple</p>
    <p>pear</p>
    <p>banana</p>
    <script src="http://d3js.org/d3.v3.min.js"></script>
    <script>
        var height = "300";
        var width = "300";

        var dataset = [2.5, 2.1, 1.7, 1.3, 0.9];
        //Define scale
        var linear =d3.scale.linear()
                    .domain([0,d3.max(dataset)])  //It must be noted here that the range is an array
                    .range([0,300]);              //It must be noted here that the range is an array


        var rectHeight=25;
        var svg=d3.select("body").append("svg")
                .attr("height",height)
                .attr("width",width)
        svg.selectAll("rect")      //Don't be short of 'All'`
            .data(dataset)
            .enter()
            .append("rect")
            .attr("x",20)
            .attr("y",function(d,i){
                return i * rectHeight;
            })
            .attr("height",rectHeight-2)
            .attr("width",function(d){
                return linear(d);   //That's where the scale is
            })
    </script>
</body>

</html>

Posted by sincspecv on Fri, 03 Apr 2020 21:16:02 -0700