In this section, we will learn how to create line charts using D3.js. Line charts are useful for visualizing data trends over time or other continuous variables. We will cover the following steps:

  1. Setting Up the SVG Canvas
  2. Loading and Parsing Data
  3. Creating Scales and Axes
  4. Drawing the Line
  5. Adding Interactivity

  1. Setting Up the SVG Canvas

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Line Chart with D3.js</title>
    <script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
    <svg width="800" height="400"></svg>
    <script src="line-chart.js"></script>
</body>
</html>

In the line-chart.js file, we will start by selecting the SVG element and setting its dimensions.

const svg = d3.select("svg");
const margin = { top: 20, right: 30, bottom: 30, left: 40 };
const width = +svg.attr("width") - margin.left - margin.right;
const height = +svg.attr("height") - margin.top - margin.bottom;

const g = svg.append("g")
    .attr("transform", `translate(${margin.left},${margin.top})`);

  1. Loading and Parsing Data

Next, we will load and parse the data. For this example, let's assume we have a CSV file named data.csv with the following structure:

date,value
2023-01-01,100
2023-01-02,110
2023-01-03,120
...

We will use D3 to load and parse this data.

d3.csv("data.csv").then(data => {
    data.forEach(d => {
        d.date = new Date(d.date);
        d.value = +d.value;
    });

    // Continue with creating scales, axes, and drawing the line
});

  1. Creating Scales and Axes

We need to create scales to map our data values to the SVG coordinates.

const x = d3.scaleTime()
    .domain(d3.extent(data, d => d.date))
    .range([0, width]);

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

g.append("g")
    .attr("transform", `translate(0,${height})`)
    .call(d3.axisBottom(x));

g.append("g")
    .call(d3.axisLeft(y));

  1. Drawing the Line

Now, we will create a line generator and use it to draw the line.

const line = d3.line()
    .x(d => x(d.date))
    .y(d => y(d.value));

g.append("path")
    .datum(data)
    .attr("fill", "none")
    .attr("stroke", "steelblue")
    .attr("stroke-width", 1.5)
    .attr("d", line);

  1. Adding Interactivity

To make the chart more interactive, we can add tooltips that display the data values when hovering over the line.

const focus = g.append("g")
    .attr("class", "focus")
    .style("display", "none");

focus.append("circle")
    .attr("r", 4.5);

focus.append("text")
    .attr("x", 9)
    .attr("dy", ".35em");

svg.append("rect")
    .attr("transform", `translate(${margin.left},${margin.top})`)
    .attr("class", "overlay")
    .attr("width", width)
    .attr("height", height)
    .style("fill", "none")
    .style("pointer-events", "all")
    .on("mouseover", () => focus.style("display", null))
    .on("mouseout", () => focus.style("display", "none"))
    .on("mousemove", mousemove);

function mousemove(event) {
    const bisectDate = d3.bisector(d => d.date).left;
    const x0 = x.invert(d3.pointer(event)[0]);
    const i = bisectDate(data, x0, 1);
    const d0 = data[i - 1];
    const d1 = data[i];
    const d = x0 - d0.date > d1.date - x0 ? d1 : d0;
    focus.attr("transform", `translate(${x(d.date)},${y(d.value)})`);
    focus.select("text").text(d.value);
}

Summary

In this section, we learned how to create a line chart using D3.js. We covered the following steps:

  • Setting up the SVG canvas
  • Loading and parsing data
  • Creating scales and axes
  • Drawing the line
  • Adding interactivity

By following these steps, you can create a basic line chart and enhance it with interactive features. In the next section, we will explore how to create pie charts.

© Copyright 2024. All rights reserved