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.
Monday, January 16, 2017

Best syntax highlighter for blogs and websites

Few months back I started sharing my codes and programming experience on my blog. I was looking for simple and best solution to highlight the code samples on my blog. There are many online tools which helps you to generate the HTML code which can be directly used on your website with highlighted styles. These online tools works fine, but it generates a lot of HTML and CSS. So I found it's alternate solution "code-prettify" which is much simpler and easy to integrate.

Step 1 - Just include the library & you are done with its setup
Just include below script in your blog / website before closing of head tag. Once it's done you can simply make use of tag to highlight your code. Check the sample code explained in step 2 to learn how to use this script.
<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script>

Step 2 - Copy the code block in PRE tag with mentioned class
It's very simple to use, you simply have to use PRE tag and give it a class "prettyprint". We also need to specify the second CSS class for script to understand which programming language colour formatting pattern to use. In below example I have used class "lang-html". This will notify script that my code block needs HTML formatting.
<pre class="prettyprint lang-html">
      Your code block here
</pre>
Highlighting PHP code
<pre class="prettyprint lang-PHP">
<?php
 echo "Hello Friends";
?>
</pre>
Highlighting JavaSctipt code
<pre class="prettyprint lang-javascript">
  var DM = 'Hello friends';
</pre>
Note - It works perfectly with many other languages, please check their github link for more details.


HTML5 Way to do the same
If you wish to use standard HTML5 elements to highlight your code then you can use following code block.
<pre class="prettyprint"><code class="language-python">
class Employee:
    def __init__(self, name):
     self.name = name

    def outputName(self):
     print "Name = %d" % Employee.name
</code></pre>

Sunday, January 15, 2017

Sample code to add tooltip to d3js chart

Last few weeks I have been writing the posts related to data visualisations using D3.js charting library. Initially I have shared the sample code to explain simple line chart. My previous post was about adding the grid lines to chart and in this post I want to help you all with an example of adding tooltips to our chart points.


Sample code to add tooltip to your charts



While working on charts, some time we come across the situations where we need to show data on mouseover event. Let's consider an example when we need to show x & y axis values of the data point on mouseover. In such situations adding a tooltip to chart points is best way to show such type of data. I usually create an empty DIV with class as tooltip and append it to the body. Then we need an event to unhide this DIV. In D3.js we can use "mouseover" event of the chart point to unhide the tooltip. Following is the sample code which you can use directly to show the tooltip on your chart.

Step 1 - Append an empty DIV to body
// Define the div for the tooltip
var tooltipDiv = d3.select("body").append("div") 
    .attr("class", "tooltip");
In above code we are adding an empty DIV to the body and giving it a class "tooltip" with attr method.

Step 2 - Apply style to the tooltip DIV
div.tooltip { 
    position: absolute;   
    text-align: center;   
    padding: 10px; 
    font: 12px sans-serif;  
    border-radius: 8px;   
    pointer-events: none;   
}
You can use your styling here to design skin of your tootltip element.

Step 3 - configure mouseover and mouseout events to hide/unhide tooltip
.on("mouseover", function(d) {  
         
// code block for tooltip
tooltipDiv.transition()  
    .duration(200)  
    .style("opacity", .9);  
tooltipDiv.html(d.year + ' : ' + d.sale) 
    .style("background", pointColor)  
    .style("left", (d3.event.pageX) - 30 + "px")  
    .style("top", (d3.event.pageY - 40) + "px"); 
})     
.on("mouseout", function(d) {  

tooltipDiv.transition()  
    .duration(500)  
    .style("opacity", 0); 
});    
This is last and most important step, we simply have to write a code to hide the tooltip on mouseover event and hide it on mouseout event. You have to write this code block while preparing the points on the chart. If you are confuse about how to place this code then please check the above demo link and check the working example.
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);

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.

Tuesday, January 3, 2017

PHP script to import CSV data to MySQL table

While populating the database, many time we come across the situation where we need to use old backups in different file formats. It's not necessary that every time you will get the data in .sql format. While working on one of my latest PHP application, I had to use Excel & CSV files to dump one of my MySQL table. So I thought of sharing the script on my blog.

Step 1 - Create MySQL database connection
Let's first create a connection to database using following code.
    // Open a connection to your MySQL database
    $host        ='localhost';  // Host Name.
    $db_user     = 'root';      //User Name
    $db_password = 'root';      //Password
    $db          = 'test';      // Database Name.

    $conn        = mysql_connect($host,$db_user,$db_password) 
                   or die (mysql_error());

    mysql_select_db($db) or die (mysql_error());

Step 2 - Read from file(CSV) & inserting in to database
Once the database connection is created and the database is selected we can simply use the following code to read the csv file. I have used the php method fgetcsv() to accomplish our job. PHP have many file reading methods but the benefit of using this method is it's capability to parse the CSV fields and returns an array. So our job becomes easy as we get one array per CSV file row.

$filename = '/path/to/file.csv';
 
// check file size here
if($filename!='' && filesize($filename)>0)
 {
 // to deal with Mac line endings
 ini_set('auto_detect_line_endings',TRUE);
  
 $file = fopen($filename, "r");
  
 while (($csvData = fgetcsv($file, 2000, ",")) !== FALSE)
 {
  $sql = "INSERT INTO 
              tableName 
          (`field1`,
           `field2`,
           `field3`,
           `field4`) 
              VALUES 
          ('".$csvData[0]."', 
           '".$csvData[1]."',
           '".$csvData[2]."',
           '".$csvData[3]."');
         ";
   mysql_query($sql);
 }
        
 fclose($file);

 ini_set('auto_detect_line_endings',FALSE);
  
 echo 'CSV File has been successfully Imported'; 
 }
 else{
   echo 'Invalid File:Please Upload CSV File';
 }
If you read the code carefully, you can notice the use of auto_detect_line_endings directive is set to TRUE before reading the CSV file. This is recommended practice by php.net while using fgetcsv() method.
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