How to build a basic line in D3.js | by Angelica Lo Duca | Towards Data Science

When dealing with data, one of the most important aspects is their presentation. For this reason, different tools and techniques exist for data visualization. In this tutorial, I will show you how to build a basic line in D3.js. D3.js is one of the most powerful libraries for data visualization in javascript. At this link you can find some basic tutorials to learn D3.js.
The code can be downloaded from my Github repository and it is freely inspired to this example, extracted from d3 data gallery.
Firstly, we start with data. We consider data related to the number of tourists arrivals in Italy, France, Spain, Germany, and United Kingdom from 1990 to 2019.
We have a column for dates and another 5 columns, one for each Country. Then we start to build the HTML code:
<!DOCTYPE html><html>  <head>     <meta charset="utf-8">     <script src="https://d3js.org/d3.v4.js"></script> </head> <body>     <div id="line"></div> </body></html>
Note that we use the version 4 of d3. Within the body we create a div which will contain the line. Now we can write the script, which will be inserted in the body.
We set the dimensions and the margins of the graph:
var margin = {top: 50, right: 30, bottom: 30, left: 100},    width = 600 - margin.left - margin.right,    height = 400 - margin.top - margin.bottom;
and we append a svg element to the div created in the HTML code and we specify their dimensions. We also add a grouping element g to the svg and we translate it to the margin.left and margin.top:
var svg = d3.select("#line")    .append("svg")    .attr("width", width + margin.left + margin.right)    .attr("height", height + margin.top + margin.bottom)    .append("g")    .attr("transform",          "translate(" + margin.left + "," + margin.top + ")");
Now we can read the CSV, by using the function d3.csv(data, preprocessing_function, processing_function) , where data represent the CSV data, the preprocessing_function permits to format data according to some criteria, the processing_function executes the operations needed to build the graph.
We define the following preprocessing_function (note that we omit the function name, because we will put it inside the d3.csv function and a name is not needed):
  function(d){    return {       date : d3.timeParse("%Y-%m-%d")(d.date),       IT : d.IT ,       FR : d.FR,       DE : d.DE,       ES : d.ES,       UK : d.UK}  },
The only useful thing that we do is parsing dates as object dates. The other fields remain constant. Now we can define the processing_function. This function requires as input data contained in the CSV file.
We add the X axis, using a time scale. We define the domain, which contains the range of possible values for the axis and the range, which contains the dimensions of the axis within the svg image.
var x = d3.scaleTime()      .domain(d3.extent(data, function(d) { return d.date; }))      .range([ 0, width ]);
We append the axis at the bottom of the svg object:
svg.append("g")      .attr("transform", "translate(0," + height + ")")      .call(d3.axisBottom(x));
Similarly, we build the y axis, where the domain is specified by the maximum value in data. In our case, the maximum value is given by the United Kingdom series:
var y = d3.scaleLinear()      .domain([0, d3.max(data, function(d) { return +d.UK; })])      .range([ height, 0 ]);
We append the y axis to the left of the svg object:
svg.append("g")     .call(d3.axisLeft(y));
Now we build a label for the y axis, we rotate it of 90 degrees and we append it to the svg object.
svg.append("text")      .attr("transform", "rotate(-90)")      .attr("y", 0 - margin.left)      .attr("x",0 - (height / 2))      .attr("dy", "1em")       .attr("font-size", "12px")      .style("text-anchor", "middle")      .text("Total Number of Tourists Arrivals");
We can add also a title, simply by adding another text at the top of the svg object:
svg.append("text")      .attr("y", 0 - margin.top)      .attr("x",(width / 2))      .attr("dy", "1em")      .attr("font-weight", "bold")      .attr("font-size", "16px")      .style("text-anchor", "middle")      .text("Total Number of Tourists Arrivals for Italy");
We can define a different color for each country. This can be done by defining a palette of colors. We define an array called countries , containing all the countries identifiers.
var countries = ['IT', 'FR','DE','UK','ES']; var color = d3.scaleOrdinal()     .domain(countries)     .range(['#e41a1c','#377eb8','#4daf4a','#984ea3','#ff7f00'])
We can add a line for each country. We use the svg element called path and we define its properties. Note that the color depends on the country.
for(var i = 0; i < countries.length; i++) {     svg.append("path")       .datum(data)       .attr("fill", "none")       .attr("stroke", function(d){ return color(countries[i]) })       .attr("stroke-width", 1.5)       .attr("d", d3.line()                 .x(function(d) { return x(d.date) })        .y(function(d) { return y(d[countries[i]]) })        ) }
We can also draw a legend. The legend is composed of a rectangle, specifying the color, and a text, specifying the country identifier.
var lineLegend = svg.selectAll(".lineLegend").data(countries)     .enter().append("g")     .attr("class","lineLegend")     .attr("transform", function (d,i) {      position = width - margin.right            return "translate(" + position + "," + (i*20)+")";        });lineLegend.append("text").text(function (d) {return d;})     .attr("transform", "translate(15,9)"); //align texts with boxeslineLegend.append("rect")     .attr("fill", function (d, i) {return color(d); })     .attr("width", 10).attr("height", 10);
In this tutorial, I have illustrated the procedure to build a basic line chart in d3.js, which is a low-level JS library to manipulate the HTML and build very powerful SVG objects. In summarizing, the steps to build the graph are the following:
On the HTML page, create a div tag statically, which will contain the chartWithin the JS script:
read data for example from CSV files
format the data according to what it is used for
retrieve the div and hang an svg object
hang the x and y axes on the svg object and assign them the domain (set of possible values) and the range (dimensions)
hang on the svg object a line, a rectangle, or a point for each data
hang a legend on the svg object (possibly)
hang a title on the svg object.
medium.datadriveninvestor.com
towardsdatascience.com
towardsdatascience.com
You can use the d3-annotation library.
Continue reading here.
Follow me on Medium
Sign up for my newsletter
Connect on LinkedIn
Follow me on Twitter
Follow me on Facebook
Follow me on Github