Scatter plots are a powerful way to visualize the relationship between two variables. In this section, we will learn how to create scatter plots using D3.js. We will cover the following topics:

  1. Understanding Scatter Plots
  2. Setting Up the SVG Canvas
  3. Binding Data to Circles
  4. Adding Axes
  5. Styling the Scatter Plot
  6. Practical Exercise

  1. Understanding Scatter Plots

A scatter plot displays points on a two-dimensional plane, where each point represents an observation in the dataset. The position of each point is determined by the values of two variables, one plotted along the x-axis and the other along the y-axis.

  1. Setting Up the SVG Canvas

First, we need to set up the SVG canvas where our scatter plot will be drawn.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Scatter Plot with D3.js</title>
    <script src="https://d3js.org/d3.v6.min.js"></script>
    <style>
        .axis path,
        .axis line {
            fill: none;
            shape-rendering: crispEdges;
        }
        .axis text {
            font-family: sans-serif;
            font-size: 12px;
        }
    </style>
</head>
<body>
    <svg width="600" height="400"></svg>
    <script>
        // JavaScript code will go here
    </script>
</body>
</html>

  1. Binding Data to Circles

Next, we will bind our data to circles in the SVG canvas. Let's assume we have the following dataset:

const data = [
    { x: 30, y: 20 },
    { x: 85, y: 90 },
    { x: 45, y: 50 },
    { x: 60, y: 30 },
    { x: 20, y: 80 },
    { x: 90, y: 60 }
];

We will use D3.js to create circles for each data point.

const svg = d3.select("svg");
const width = +svg.attr("width");
const height = +svg.attr("height");

const xScale = d3.scaleLinear()
    .domain([0, d3.max(data, d => d.x)])
    .range([0, width]);

const yScale = d3.scaleLinear()
    .domain([0, d3.max(data, d => d.y)])
    .range([height, 0]);

svg.selectAll("circle")
    .data(data)
    .enter()
    .append("circle")
    .attr("cx", d => xScale(d.x))
    .attr("cy", d => yScale(d.y))
    .attr("r", 5);

  1. Adding Axes

To make our scatter plot more informative, we need to add axes.

const xAxis = d3.axisBottom(xScale);
const yAxis = d3.axisLeft(yScale);

svg.append("g")
    .attr("transform", `translate(0, ${height})`)
    .call(xAxis);

svg.append("g")
    .call(yAxis);

  1. Styling the Scatter Plot

We can enhance the appearance of our scatter plot by adding some styles.

svg.selectAll("circle")
    .attr("fill", "steelblue")
    .attr("stroke", "black")
    .attr("stroke-width", 1);

  1. Practical Exercise

Exercise: Create a Scatter Plot

Objective: Create a scatter plot using the provided dataset and customize it with different colors and sizes for the circles.

Dataset:

const data = [
    { x: 10, y: 20, size: 5, color: "red" },
    { x: 40, y: 90, size: 10, color: "blue" },
    { x: 60, y: 50, size: 15, color: "green" },
    { x: 80, y: 30, size: 20, color: "purple" },
    { x: 20, y: 70, size: 25, color: "orange" },
    { x: 90, y: 60, size: 30, color: "pink" }
];

Steps:

  1. Set up the SVG canvas.
  2. Bind the data to circles.
  3. Add axes.
  4. Style the circles based on the size and color properties.

Solution:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Scatter Plot Exercise</title>
    <script src="https://d3js.org/d3.v6.min.js"></script>
    <style>
        .axis path,
        .axis line {
            fill: none;
            shape-rendering: crispEdges;
        }
        .axis text {
            font-family: sans-serif;
            font-size: 12px;
        }
    </style>
</head>
<body>
    <svg width="600" height="400"></svg>
    <script>
        const data = [
            { x: 10, y: 20, size: 5, color: "red" },
            { x: 40, y: 90, size: 10, color: "blue" },
            { x: 60, y: 50, size: 15, color: "green" },
            { x: 80, y: 30, size: 20, color: "purple" },
            { x: 20, y: 70, size: 25, color: "orange" },
            { x: 90, y: 60, size: 30, color: "pink" }
        ];

        const svg = d3.select("svg");
        const width = +svg.attr("width");
        const height = +svg.attr("height");

        const xScale = d3.scaleLinear()
            .domain([0, d3.max(data, d => d.x)])
            .range([0, width]);

        const yScale = d3.scaleLinear()
            .domain([0, d3.max(data, d => d.y)])
            .range([height, 0]);

        const xAxis = d3.axisBottom(xScale);
        const yAxis = d3.axisLeft(yScale);

        svg.append("g")
            .attr("transform", `translate(0, ${height})`)
            .call(xAxis);

        svg.append("g")
            .call(yAxis);

        svg.selectAll("circle")
            .data(data)
            .enter()
            .append("circle")
            .attr("cx", d => xScale(d.x))
            .attr("cy", d => yScale(d.y))
            .attr("r", d => d.size)
            .attr("fill", d => d.color)
            .attr("stroke", "black")
            .attr("stroke-width", 1);
    </script>
</body>
</html>

Conclusion

In this section, we learned how to create scatter plots using D3.js. We covered setting up the SVG canvas, binding data to circles, adding axes, and styling the scatter plot. We also provided a practical exercise to reinforce the concepts learned. In the next module, we will explore more advanced visualizations.

© Copyright 2024. All rights reserved