Tuesday, December 27, 2016

Sample code for creating simple line chart using D3.js

In my previous blog post I have explained about SVG and its coordinate system. To start coding line chart visualizations in D3.js it's very important to have some basic knowledge of SVG, so if you are not aware of the SVG elements then please spend some time to read my previous blog post.


See it before you learn it.



Lets Start writing your first line chart visualization. Before we actually start writing the visualization lets spend some time to understand how to include the D3.js library in your HTML page and then about creating the skeleton of the visualization.

1. Include D3.js library
Including the library and setting up the skeleton is kind of common task while creating multiple visualizations. You can download the D3.js library from github or you can also use it directly from CDN. Let's first include the library in our HTML page.

<!DOCTYPE html> 
<html> 
<head> 
  <script type="text/javascript" src="d3.min.js"></script>
</head> 
<body> 
  <p> line chart using D3.js</p> 
</body> 
2. Create data for chart
I am going to use following data for this chart. You can update this data as well as its format if its required.
var chartConfig = {
data:[{
   "sale": "202",
   "year": "2000"
  }, {
   "sale": "215",
   "year": "2001"
  }, {
   "sale": "179",
   "year": "2002"
  }, {
   "sale": "199",
   "year": "2003"
  }, {
   "sale": "134",
   "year": "2003"
  }, {
   "sale": "176",
   "year": "2010"
  }]
};
3. Configure SVG element
As I mention SVG is the basic of visualizations so first of all, we have to configure and append the SVG element to the page body. Please have a close look att the below sample code & note the attributes which are set in "svgConfig" object.

"width", "height" & "margin" are basic and important attributes which we have to set. In below example, I am creating the SVG element of size 300 X 600. You can configure these properties as per your requirement.
var svgConfig = {
 id:"mySvg",
 width:600,
 height:300,
 margin : {
  top: 20,
  right: 20,
  bottom: 20,
  left: 50
   }
 };
Now lets add the SVG element to the document.
var bodySelection = d3.select("body");

var svgSelection  = bodySelection.append("svg")
        .attr("id", svgConfig.id)
        .attr("width",svgConfig.width)
        .attr("height",svgConfig.height);
You can run your HTML page in browse and check the source. you should be able to see the SVG element created with the mentioned height and width. If you are not able to see the same then please check the code again and follow the steps until you get your SVG ready.

4. Create X & Y Scale
Once your SVG element is ready and appended to document body we can start creating X and Y scales for our chart. D3.js supports quantitative scale as well as oridinal scale. As this is our first example we can start with simple quantitative scale. Each D3.js scale is nothing but a function which transfers domain in to range. We will learn these terms in detail as we move in detail with D3.js. So for now just proceed with the following code block.
xScale = d3.scale.linear()
           .range([
               svgConfig.margin.left, svgConfig.width - svgConfig.margin.right
            ])
            .domain([
               d3.min(chartConfig.data, function(d) {return +d.year;}),
               d3.max(chartConfig.data, function(d) {return +d.year;})
            ]);
Range & Domain - The values which we have passed to range method are nothing minimum and maximum plottable area for X-axis. Similarly, if you check the values passed to the domain method are nothing but minimum and maximum points to be plotted on X-axis. So the scale is the method which will transform the domain into range within given boundaries.
Similarly, we have to create Y Scale. Have a look at the following code & try to understand the parameters for range and domain methods.
yScale = d3.scale.linear()
           .range([
                 svgConfig.height - svgConfig.margin.top, 
                 svgConfig.margin.bottom
            ])
           .domain([
               d3.min(chartConfig.data, function(d) {return +d.sale;}),
               d3.max(chartConfig.data, function(d) {return +d.sale;})
            ]);
5. Create X & Y axis
Once X & Y scales are created we can use those objects to create X & Y Axis. D3.js provides a method (d3.svg.axis) to add vertical and horizontal axis on svg element.
xAxis = d3.svg.axis()
  .scale(xScale);

yAxis = d3.svg.axis()
  .orient("left")
  .scale(yScale);
Let's add X axis to the chart.
After running following code it will add the X-axis at the top of the SVG element. After this step you can run the script on browser and have a look at the location of the X axis on your chart. In next step we will transform it to it's correct position which is nothing but at the bottom of the chart area.
svgSelection.append("svg:g")
.attr("id","xAxis")
.call(xAxis);
Output
line chart sample

Let's transform X axis to its correct position.
As I mention in my earlier posts that SVG 0,0 points starts from top left instead of top-bottom, the above X-axis will get plotted at the top of the chart. In next step we will bring it to its correct position. There are many alternative ways of plotting the X-axis but I am trying to explain it in detail so you will understand the core D3.js. Now try below code and again run your code in the browser.
d3.select("#xAxis")
.attr("transform", "translate(0," + (svgConfig.height - svgConfig.margin.bottom) + ")");
Above line is nothing but an example of use of the transform property which is set using attr method of the D3.js. Kindly note the parameters passed to this method. Its translating the axis from 0 to SVG height - margin.

Output
after moving xaxis to charts bottom


Now lets add Y axis to the chart
// add yaxis to chart, but this will not add it to correct oorientation
svgSelection.append("svg:g")
.attr("id","yAxis")
.call(yAxis);
 
// apply transform logic to bring it to correct place
d3.select("#yAxis")
.attr("transform", "translate(" + (svgConfig.margin.left) + ",0)")   


After adding X and Y axis to the chart, please check your browser and it should look like below image.
chart after adding x and y axis

6. As our axis and scales are ready, let's plot the points.
In first step, we have created a data object for our chart. This data object is nothing but the points which we need to plot on our chart. After that we have created scales and axis for our chart. This is called as initial setup for your chart. Once this is done you can start writing code for plotting the data points.

As this example is to help you to learn how to draw the simple line chart using D3.js, we have to use line function of d3.svg. Checkout the following code to learn how can we generate line using D3.js.
var lineSelection = d3.svg.line()
   .x(function(d){
    return xScale(d.year);
   })
   .y(function(d){
    return yScale(d.sale)
   });
Finally apppend the line object to our SVG element by using append method.
Following sample code will append the line created in above step. attr is the D3.js method which allows us to set multiple line parameters like stroke, stroke-width, fill etc. There are many other properties which are related to line object, you can check the documentation section of D3.js to find details of all of them.
svgSelection.append("svg:path")
 .attr('d', lineSelection(chartConfig.data))
 .attr('stroke', 'green')
 .attr('stroke-width', 2)
 .attr('fill', 'none');
Output
final output of your line chart code


Next > Learn to create multi-line chart using D3.js

No comments:

Post a Comment