Showing posts with label Visualizations. Show all posts
Showing posts with label Visualizations. Show all posts
Wednesday, August 2, 2017

How to create horizontal bar chart using d3js JavaScript charting library

I received lot of requests by many d3js beginners about "how to create a horizontal bar chart using d3js" along with sample code. I think I have not posted anything related to d3js after my last article. So almost after 2 months, I am writing this post on d3js. I have prepared a sample code to show the distance in meters covered by every participant in a running race. It's very simple example with distance in meters is on X-axis and participant's names are on Y-axis. Just for the change, I have moved my X-Axis to the top.

Sample code for creating horizontal bar chart in d3js



Step 1 - Append an empty DIV to body with id as "chart"
<!-- horizontal bar chart -->
<div id="chart">  </div>
Step 2 - Prepare JSON data
var data = [{
   "name": "Rohit",
   "value": 120
  }, {
   "name": "Sanket",
   "value": 116
  }, {
   "name": "Vivek",
   "value": 109
  }, {
   "name": "Richa",
   "value": 94
  }, {
   "name": "Ricky",
   "value": 90
  }, {
   "name": "soniya",
   "value": 84
  }, {
   "name": "Nilesh",
   "value": 107
  }, {
   "name": "Sweety",
   "value": 66
  }];
Note : This is the data which will be displayed in the chart, your values may change and you can update this JSON as per requirements.

Step 3 - Create self injecting method with two parameters to it - holder & data
You can also give some name to the method and pass the parameters. I am giving the explanation of the steps which I have used in my example so can do the changes in your code if you are comfortable. This method takes care of creating the x and y axis and drawing the rectangle etc.
(function(holder,data){
// code to generate chart goes here.
})("#chart", data);

If you are completely new to d3js and don't know about how to draw x and y axis using SVG then please refer to my first post. In this post, I am explaining the changes required for only the horizontal bar chart.

Step 4 - Once X and Y axis are ready, use below script to generate horizontal rectangles.
So once your axis is ready then you can add following code in order to generate bars on the chart. Basically, you will be generating rectangle elements using d3js methods. In this, we have to specify x-y coordinates, width, and height of each rectangle. Have a look at the below code and you will understand what is happening.
 svg.selectAll('.bar')
 .data(data)
 .enter().append('rect')
 .attr('class', 'bar barColor')
 .attr('x', function(d) { return x(d3.min(data, function(d) {return +d.value;})); })
 .attr('y', function(d) { return y(d.name); })
 .attr('width', function(d) { return x(d.value); })
 .attr('height', y.rangeBand());
You can check last 4 lines of above code, I am starting the rectangle from the starting point of the x axis which is nothing but the minimum of the d.value from data object. Similarly I am setting the height and width of the rectangle.

I hope this example code will help beginners to understand how svg bar element can be used to generate horizontal bar charts using d3.js. Best of luck.

Tuesday, January 17, 2017

Scale the circle radius in d3js chart on mouseover

D3.js is really an amazing charting library and I think I can't stop writing about it's features and sample codes. D3.js is something like, no limitations on what you can do with charts. You think about it and it's possible with this library. Today while working on one example, I came across a situation where most of the chart area was covered with points and paths because of huge data points. In this case, we can add small animation to the path points. In this type of animation if user mouseover on some data point, then we increase the radius of the circle with transition effect and on mouse out we bring it back to the original radius. So let's learn something about circle animation in this post.

I have tried to explain the code in pictorial way in below image, please check it and first and try to understand the logic.


Check line number 229 in my example to understand how to place the below code block. You will first have to select the circle and then configure its mouseover event as described below.

.on("mouseover", function(d) {  
         
  d3.select(this)
    .transition()
    .duration(300)
    .attr("r", 6);

});

Once this is done, you have to configure the mouse out event to bring circle back to its original size.
Wednesday, January 11, 2017

How to add grid lines to d3js chart

In my previous blog post I have explained how to add multiple lines to the d3.js line chart with an example. But, if you check them carefully then you can notice that, I have not added any grid lines in any of the examples. I recommend to read my previous post before continue reading this article for better understanding of the code but it's not mandatory. So, lets check how easy is to add the grid lines to x and Y axis in d3.js charts. I have already prepared one sample on jsfiddle, please have a look at it first and then I will explain the code block to generate the grid lines.

Sample Code - D3.js chart with grid lines on X & Y Axis


In above example, I have used the method "innerTickSize" to generate the grid lines on X-axis. Have a look at the below code sample to learn how innerTickSize method works. The parameter to this method during the generation of x-Axis is nothing but the height of the vertical grid lines and during the generation of y-axis its as equal as the width of horizontal grid lines.

In both the cases we can make use of svgConfig.height and svgConfig.height variables. For X-Axis I have used random number 56, but you can configure this number as svgConfig.padding as well.
//let's create the axes using the scales with grid lines
xAxis = d3.svg.axis()
 .scale(xScale)
 .tickFormat(d3.format("d"))
        .innerTickSize(-(svgConfig.height-56)); 
   
yAxis = d3.svg.axis()
 .orient("left")
 .scale(yScale)
        .innerTickSize(-svgConfig.width);


Next > Learn to add tooltip to the chart


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

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.