Friday, June 12, 2026
HomeLanguagesJavascriptD3.js scaleOrdinal() Function

D3.js scaleOrdinal() Function

The d3.scaleOrdinal() function is used to create and return the ordinal scale which has the specified range and domain. If the domain and range are not given then both are set to empty array. These types of scales have a discrete domain and range.

Syntax:

d3.scaleOrdinal([[domain, ]range]);

Parameters:  This function takes two parameters as given above and described below:

  • domain: It defines the minimum and maximum value for the scale.
  • range:  Every value in domain maps with value in the range.

Return Values: This function does not return anything.

Example 1:

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" path1tent=
        "width=device-width, 
        initial-scale=1.0" />
    <script src=
        "https://d3js.org/d3.v4.min.js">
    </script>
</head>
  
<body>
    <script>
  
        // Creating the Ordinal scale.
        var ordinal = d3.scaleThreshold()
  
            // Setting domain for the scale
            .domain([1, 2, 3, 4])
            .range([10, 20, 30, 40]);
          
        console.log("The value of ordinal(1) is: ",
                ordinal(1));
        console.log("The value of ordinal(2) is: ",
                ordinal(2));
        console.log("The value of ordinal(3) is: ",
                ordinal(3));
    </script>
</body>
  
</html>


Output:

Example 2:

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" path1tent=
        "width=device-width, 
        initial-scale=1.0" />
  
    <script src=
        "https://d3js.org/d3.v4.min.js">
    </script>
</head>
  
<body>
    <script>
        // Creating the Ordinal scale.
        var ordinal = d3.scaleThreshold()
  
            // Setting domain for the scale
            .domain([1, 2, 3, 4])
            .range(["String1", "string2", 
                    "string3", "string4"]);
  
        console.log("The value of ordinal(1) is: ",
                ordinal(1));
        console.log("The value of ordinal(2) is: ",
                ordinal(2));
        console.log("The value of ordinal(3) is: ",
                ordinal(3));
        console.log("When value given is not"
                + " in the domain:")
        console.log("The value of ordinal(4) is: ",
                ordinal(10));
    </script>
</body>
  
</html>


Output:

RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6897 POSTS0 COMMENTS
Nicole Veronica
12013 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6963 POSTS0 COMMENTS