In this section, we will delve into two fundamental types of scales in D3.js: linear and ordinal scales. Understanding these scales is crucial for mapping data values to visual properties like position, length, and color in your visualizations.

What are Scales?

Scales are functions that map from an input domain to an output range. They are essential in D3.js for transforming data values into visual representations.

Key Concepts:

  • Domain: The set of input values.
  • Range: The set of output values.
  • Scale Function: A function that maps a domain value to a range value.

Linear Scales

Linear scales are used for continuous data. They map a continuous input domain to a continuous output range. This is particularly useful for data that has a linear relationship.

Creating a Linear Scale

To create a linear scale in D3.js, you use the d3.scaleLinear() function.

// Example of a linear scale
const linearScale = d3.scaleLinear()
    .domain([0, 100])  // Input domain
    .range([0, 500]);  // Output range

console.log(linearScale(50));  // Output: 250

Explanation:

  • Domain: [0, 100] - The input values range from 0 to 100.
  • Range: [0, 500] - The output values range from 0 to 500.
  • Scale Function: linearScale(50) maps the input value 50 to the output value 250.

Practical Example: Mapping Data to Pixel Values

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Linear Scale Example</title>
    <script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
    <svg width="600" height="100"></svg>
    <script>
        const svg = d3.select("svg");

        const data = [10, 20, 30, 40, 50];

        const xScale = d3.scaleLinear()
            .domain([0, d3.max(data)])
            .range([0, 600]);

        svg.selectAll("circle")
            .data(data)
            .enter()
            .append("circle")
            .attr("cx", d => xScale(d))
            .attr("cy", 50)
            .attr("r", 5);
    </script>
</body>
</html>

Explanation:

  • Data: [10, 20, 30, 40, 50]
  • xScale: Maps the data values to pixel values on the x-axis.
  • SVG Circles: Plots circles at the corresponding x positions.

Ordinal Scales

Ordinal scales are used for categorical data. They map a discrete domain to a discrete range.

Creating an Ordinal Scale

To create an ordinal scale in D3.js, you use the d3.scaleOrdinal() function.

// Example of an ordinal scale
const ordinalScale = d3.scaleOrdinal()
    .domain(["A", "B", "C", "D"])
    .range(["red", "green", "blue", "orange"]);

console.log(ordinalScale("A"));  // Output: "red"

Explanation:

  • Domain: ["A", "B", "C", "D"] - The input values are categories.
  • Range: ["red", "green", "blue", "orange"] - The output values are colors.
  • Scale Function: ordinalScale("A") maps the input value "A" to the output value "red".

Practical Example: Coloring Bars in a Bar Chart

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ordinal Scale Example</title>
    <script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
    <svg width="400" height="200"></svg>
    <script>
        const svg = d3.select("svg");

        const data = ["A", "B", "C", "D"];

        const colorScale = d3.scaleOrdinal()
            .domain(data)
            .range(["red", "green", "blue", "orange"]);

        svg.selectAll("rect")
            .data(data)
            .enter()
            .append("rect")
            .attr("x", (d, i) => i * 100)
            .attr("y", 50)
            .attr("width", 80)
            .attr("height", 100)
            .attr("fill", d => colorScale(d));
    </script>
</body>
</html>

Explanation:

  • Data: ["A", "B", "C", "D"]
  • colorScale: Maps the categories to colors.
  • SVG Rectangles: Draws rectangles with the corresponding colors.

Exercises

Exercise 1: Create a Linear Scale

Create a linear scale that maps the domain [0, 200] to the range [0, 1000]. Use this scale to map the value 150.

Solution:

const linearScale = d3.scaleLinear()
    .domain([0, 200])
    .range([0, 1000]);

console.log(linearScale(150));  // Output: 750

Exercise 2: Create an Ordinal Scale

Create an ordinal scale that maps the domain ["apple", "banana", "cherry"] to the range ["#ff0000", "#ffff00", "#ff00ff"]. Use this scale to map the value "banana".

Solution:

const ordinalScale = d3.scaleOrdinal()
    .domain(["apple", "banana", "cherry"])
    .range(["#ff0000", "#ffff00", "#ff00ff"]);

console.log(ordinalScale("banana"));  // Output: "#ffff00"

Summary

In this section, we covered:

  • The concept of scales in D3.js.
  • How to create and use linear scales for continuous data.
  • How to create and use ordinal scales for categorical data.
  • Practical examples of using these scales in visualizations.

Understanding and effectively using scales is fundamental to creating accurate and visually appealing data visualizations in D3.js. In the next section, we will explore time and logarithmic scales, which are useful for more specialized data transformations.

© Copyright 2024. All rights reserved