Thursday, January 5, 2017

Learn to create multi-line chart using d3.js with example

In this post I am going explain how can we use D3.js charting library to generate multiple lines chart with the simple example. Before you continue reading this post, I recommend to check my previous blog post to learn simple line chart using D3.js. Most of the common steps like SVG configuration, document data preparation is explained in detail in the previous post itself. As these initial steps are common while making any chart so I don't want to copy that part in this post.

See it before you learn it


1. Initial setup
Initial setup is exactly same as my previous blog post. So you can simply copy the complete code block from previous example and run it in your browser. This will show you the single line with X and Y axis. We will do the following changes in this existing code to make it multiple line charts.

2. Let's update the data for second line
In order to add the second line to our example, we will have to update "chartConfig" object. Object have only one array "data". This array is used to map the first line in our graph. As we need to add the second line, I will simply add one more array to this object "data2". So our new object will look as follows.
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"
  }],
data2:[{ 
 "sale": "200", 
 "year": "2000" 
  }, { 
 "sale": "180", 
 "year": "2001" 
  }, { 
 "sale": "195", 
 "year": "2002"
  }, { 
 "sale": "200", 
 "year": "2003"
  }, {
 "sale": "176", 
 "year": "2004"
  }, { 
 "sale": "196", 
 "year": "2010"
}]
 };
3. Let's add code to render second line
Above step is to keep the data ready to render the second line. Now as we have our data ready, we can simply use the similar code block to add the second line just by passing the new data object. Just add the below code block at the end of existing code.
// append second line to svg
 svgSelection.append("svg:path")
  .attr('d', lineSelection(chartConfig.data2))
  .attr('stroke', 'red')
  .attr('stroke-width', 2)
  .attr('fill', 'none');  
I have done only following two changes in earlier code to generate the line on SVG element.
  • I have pass new data array "chartConfig.data2" to lineSelection method.
  • Set the line stroke property to red so we can identify new line easily.

Output

To create multiple line chart you can simply create multiple data arrays and configure the above code block per line. This is simple and easiest code to generate multiple line chart using D3.js, please give your feedback and suggestions in the comment box below.

Next > How to add grid lines to chart

No comments:

Post a Comment