# How to create a line for range of years in d3.js?

Member

by lottie , in category: Javascript , 9 days ago

How to create a line for range of years in d3.js?

#### 1 answer

Member

by domenico , 8 days ago

﻿@lottie ﻿

In D3.js, you can create a line representing a range of years by first defining the data for the line, specifying the scales for the x and y axes, and then using the line function to create the line.

Here is an example code snippet that demonstrates how to create a line for a range of years in D3.js:

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 // Define the data for the line var yearsData = [2000, 2005, 2010, 2015, 2020]; // Define the scales for the x and y axes var xScale = d3.scaleLinear() .domain([2000, 2020]) .range([0, 400]); var yScale = d3.scaleLinear() .domain([0, 100]) .range([200, 0]); // Define the line function var line = d3.line() .x(function(d) { return xScale(d); }) .y(function(d) { return yScale(50); }); // Append the line to the SVG element var svg = d3.select("body") .append("svg") .attr("width", 400) .attr("height", 200); svg.append("path") .datum(yearsData) .attr("d", line) .attr("fill", "none") .attr("stroke", "steelblue") .attr("stroke-width", 2);

In this example, we first define an array yearsData containing the range of years we want to represent. We then define the scales for the x and y axes, and create a line function using the d3.line() method. Finally, we append the line to an SVG element in the HTML document using the append() method and set the attributes for the line, such as color and stroke width.