Showing posts with label Chart. Show all posts
Showing posts with label Chart. Show all posts
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

Thursday, December 22, 2016

Understanding SVG coordinate systems with an example

Before we start learning the generation of data visualizations with d3.js, lets spend some time to understand what is SVG and how does the coordination system works.


What is SVG?
  • SVG stands for Scalable Vector Graphics.
  • SVG is used to create different shapes that can be used in HTML or independently as graphics.
  • Using SVG we can draw shapes like circle, rectangles, curved lines, animations etc.
  • The most important part about using SVG is that it is scalable.
  • If we scale images, they can become pixelated or too sharp.
  • In case of SVG, the graphics scale well therefore making it a good choice for graphs for screens with varying dimensions.
  • Let’s see some simple examples using SVG.

SVG coordinate system

Please check above image and try to understand the difference between regular coordinate system and SVG coordinate system. One very important thing to notice is the locatoin of 0,0 coordinate. In gerular system its always at bottom left corner but in SVG system its at top left corner.

Let's learn this in detail with an example.

  • Create an empty HTML document and keep adding SVG elements as mentioned below
  • Add SVG element and give it height and width
  • Add a rectangle giving it `x`, `y`, ` width ` ,`height` and `fill`
  • Add a circle giving it `r`, `cx`, `cy` and `fill`

Your code should look like below image.


Save it as .html file and run in your favourite browser. You should be able to see something similar as below image.


Important points to remember
  • x starts from left corner and goes to the right.
  • So x=10 means 10 pixels to the right of the left edge
  • And x=-10 will mean 10 pixels to the left of the left edge.
  • y starts from the top and goes downwards.
  • So y=10 means 10 pixels below the top edge
  • And y=-10 will mean 10 pixels above the top edge

If you have any doubts or any query related to above example please put your comments and I would love to resolve your queries. Next post will be a example of data visualization using D3.js.

Next > Learn simple line chart using d3.js

Monday, December 19, 2016

Why d3js is best data visualization framework


As we all have learned about "Data Visualizations" in my previous blog, lets start learning the best way to generate and integrate them in web applications.

Data visualizations can be developed and integrated in regular web & even mobile applications using different JavaScript frameworks. In this blog post I would like to highlight the use of D3.js and it's comparison in terms of creating data visualizations.

What is D3.js
D3.js is a simple JavaScript based framework which is used to generate any type of data visualizations with the help of SVG ( Scalable Vector Graphics ) or canvas HTML element.

Why D3.js is better than other charting libraries
  • Free for even commercial use under BSD licence.
  • Highcharts is one of the alternative but it's a paid for commercial use.
  • Prefuse and flare – need extra browser plugin.
  • D3.js has open source community with lots of code samples.
  • As its widely used for charting so its Hireable skill :) - Check job availability here

Advantages of D3.js over other charting libraries
  • Open Source
  • Powerful Visualization
  • Interaction techniques
  • DOM manipulation
  • Freedom to design the right visual interface
  • Works without any plugin like other libraries
  • D3.js helps you bring data to life using SVG, Canvas and HTML
  • You can also integrate transitions of different SVG elements very easily

Summery
D3.js is one of the best data visualization framework and it can be used to generate simple as well as complex visualizations along with user interaction and transition effects. In my next blog I will try to explain how we can use D3.js to generate a visualization with an example.

Next > Understanding SVG coordinate systems
Friday, December 16, 2016

Understanding Data Visualizations With An Example

We all know that graphical or image representation of any data is really easy and quick way to understand. Data visualization is nothing but a way to represent the raw data in a format which is easy to understand such as pictorial or we can say graphical representation. So lets learn what is this data visualizations and its advantages.

Any type of data which is represented by a visualization allows users to compare the data, generate analytic reports, understand patterns and thus helps them to take the decision. Data Visualizations can also be interactive so that users can also drill into the pie, bar etc charts to analyze specific data. These are nothing but simple data filters which gets activated and change the complete visualization to render the selected data.

Let's take an example of any E-commerce website and it's raw(text base) sale report. If we have text/excel formatted sale report and if we need to find following points then imagine how difficult it will be.
  • Which year company did the maximum sale;
  • Which is the highest selling category;
  • Which products are best sellers/month; etc

If we get the graphical representation of same text based sale data then it will be super easy for us to find the answers of above questions and much more. This is the basic behind Data Visualizations. Check below visualization created using Line chart. This chart is representing the sale records of 11 years. With the similar approach, we can also check the data per month. The whole idea is to understand how the pictorial representation helps us to analyze the data quickly.



Summery
  • Presentation of data in graphical format.
  • High-level understanding of all kinds of data.
  • Understand patterns which is not possible without data visualizations.
  • More analytics data can be collected by end user in shorter time.