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.

Friday, February 24, 2017

Dynamically add/remove table rows using jquery

While developing complex DOM structures, many time we come across the designs where we may need to control the height of the HTML table dynamically. In many situations, the requirement is to let users manage the number of table rows. This is really a simple code and can be easily written using JavaScript and jQuery.

Before we move and check the code I want to highlight that one must know the use of jQuery methods such as "append()", "close()" & "remove()". If you know the purpose and working of these methods then this job will be a piece of cake for you.


Click to view Demo

Step 1. Copy below HTML markup for table
<table id="table">
    <tr valign="top" >
      <th scope="row"><label>Label</label></th>
      <td>
        <input type="text" id="field1" />  
        <input type="text" id="field2" />  
        <a href="javascript:void(0);" class="add">Add</a>    <a href="javascript:void(0);" class="remove">Remove</a>
 </td>
    </tr>
</table>
Note that you will have to keep one row in this table which needs to be cloned dynamically. We can also keep empty table but in that case, we will need to create a DOM object using jQuery. Let's first understand the logic of dynamically adding the rows and later on you can remove first row as well.

Step 2. jQuery code to dynamically add/remove rows of the table
$(document).ready(function(){
   $("#table").on('click','.add',function(){
    rowObj = $("#table tr:first").clone();
    $( "#table" ).append(rowObj);
 });
    $("#table").on('click','.remove',function(){
        $(this).parent().parent().remove();
    });
});

Explanation
I have used CSS selector rule "#table tr:first" to select the first row of the table. I am using .clone() method on that selector to make a copy of it and saved it in rowObj variable. This object is nothing but a DOM element which we can append to any parent. So next job is to just append the cloned DOM element to the table using "append()" method. Similarly I have used remove() method to dynamically remove the table row.
Wednesday, February 22, 2017

Simple MEAN stack application with sample code

From so many years JavaScript has escaped the limelight for the majority and was being seen as just a language to validate forms and show alerts and some other small tasks on the client side. But now JavaScript has become very powerful and it's capable enough to make you a full stack web developer. Yes, if you know JavaScript you can create web server, create beautiful UI to handle user interaction and can also write powerful API to handle all the data sent through web forms and save the data into the database.
Sounds interesting? Go through the complete tutorial to understand how can we implement a complete web application and server using JavaScript and MEAN stack.


What is MEAN stack and why you should learn it?
Let's first understand what is the meaning of this MEAN stack and how this can be useful to complete this tutorial. MEAN stack is the stack of technologies which I am going to use in this tutorial. This little bunch of technologies is well enough for writing a complete web application.

M - MongoDB
E - ExpressJS
A - AngularJS
N - Node JS

It's perfectly all right if you are not aware of any of the above technologies I am going to explain everything in detail and step by step manner. Highlevel overview of this tutorial is as follows.
  • Learn to install nodeJS.
  • How to install dependencies using package.json.
  • Create simple directory structure for our first MEAN application.
  • How to include ExpressJS to your nodejs web server
  • Writing your first web form to get inputs from user.
  • Writing your first API using ExpressJS to handle the form data.
  • Installing mondoDB server to store the data.
  • Changing the first API to not only handle the post data but to save it in database.
  • Writing your second API to fetch the records from database and return them in JSON format.

I have used Ubuntu 15.10 while preparing this tutorial so all the steps mentioned here are for Ubuntu and other linux flavors and not for windows. But the code and the main logic will remain same, only installation steps will change for windows users. Soon I will also try to write the steps for windows users as well. Really sorry for not having it right now.

Get set go,

1. Let's start with learning to install nodeJS.
Let's start by installing nodeJS on your linux machine using package manager. Please refer following commands to install nodeJS.
sudo apt-get update
sudo apt-get install nodejs
Above step will install only nodeJS on your machine but we also need some other nodeJS modules in further steps of this tutorial. So let's also have a look at the installation of Node Package Manager. Simply run following command to install NPM.
sudo apt-get install npm
Cool now we have our nodeJS and NPM ready.

2. Lets learn to install dependencies using package.json
In above step we have installed NPM, which will help us to install multiple dependencies of our application very easily. package.json is the file which have the configurations of all the dependencies of the application. So let's see how can we create this file to define dependencies of our app.

For this simply follow the below steps and learn the standard approach of setting up your node project. Let's start by creating the empty directory, I name my application as "user_info" and thus the directory. This application will accept user information so I named it user_info you can change this name.
mkdir user_info
cd user_info
Now let's create the package.json file to write metadata and module dependency of our application. A standard and efficient way to do so is to use the command "npm init". This utility will help you to create your package.json. So just hit this on your command prompt and answer the questions asked on the prompt to complete this step.
npm init
Below is the screenshot of the process to create the package.json.


I hope the process is simple and you have successfully setup your first nodeJS application with the help of NPM. Now you can browse your package.json file and check its contents. It should look something like below image.


Let's add dependencies to this file now.
Now we will update this package.json file to include our application dependenices and later on we will install all of them in a node way. You need to add one extra key called as "dependencies" as shows in below example.
{
  "name": "user_info",
  "version": "1.0.0",
  "description": "Simple application to save user information",
  "main": "index.js",
  "scripts": {
    "test": "echo \"my first MEAN stack application\""
  },
  "author": "Dhanesh Mane",
  "license": "ISC",
  "dependencies": {
    "body-parser": "latest",
    "express": "latest",
    "mongodb": "^2.2.22",
    "mongoose": "latest"
  }
}
In above step we have added 4 new dependencies to our project, now its time to install these dependencies by using below command.
npm install
Above command create new directory called as "node_modules" to save all node dependencies. There must be a new directory "node_modules" inside user_info app. please go back to console and check if all your dependencies are installed inside this directory or not. If you can see some files related to MongoDB and ExpressJS then you have your dependencies ready to use.
Lets verify the installation using following commands.


3. Lets create directory structure & some important files
While setting up your first MEAN stack application we should follow a good directory structure, I dont want to be too complex here as its our first application so I have just tried to keep it simople. Just go thgough following 4 steps and setup your structure.

1. Create directory with name "user_info/config".
2. Create empty file with name "user_info/config/database.js".
3. Create directory with name "user_info/models".
4. Create directory with name "user_info/public".

It should look something like below image.


4. Let's include express to your nodejs project and create a web server
Fun begins, let's start writing some code now. From this step we will be writing our web server and the API as most of the installation is done. So simply create a new file and name it as user_info/server.js. First of all, let's see how to include express in our nodeJS project. If you remember we have already installed express dependency in step 2 so now we just need to give its reference to include it in the project. Copy below lines of code and paste it in server.js
'use strict';
// ----- initialization
var express = require('express');
var app = express();

app.use(express.static('public'));

// ----- Routes
app.get('/',function(req, res){
   res.send('my first node server');
});

// ----- Server
var server = app.listen(3000, function () {
  
  var port = server.address().port

  console.log('Example app listening on port 3000! go to http://localhost:%s',  port)
})
Now it's a time to run your first node server. Open the command prompt, go to user_info directory and hit below command to start the server.
node server.js
Once you run above command you should see a message something like this on your prompt --> "Example app listening on port 3000! go to http://localhost:3000". If you see this then your first node server app is running properly.
Go to "http://localhost:3000" on your browser and check what you see on your browser. It must be something similar to below image.


5. Let's create a simple form to accept user inputs
I don't want to explain this step in detail, but you can simply copy below sample code and paste in new file "public/user_info.html"
<!DOCTYPE html>
<html lang="en">
<head>
  <title>User Info</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Enter User Information</h2>
  <form action="/save_user" method="post">
    <div class="form-group">
      <label for="email">Email:</label>
      <input name="email" type="text" class="form-control" id="email" placeholder="Enter email">
    </div>
    <div class="form-group">
      <label for="name">Full Name:</label>
      <input name="name" type="text" class="form-control" id="name" placeholder="Enter full name">
    </div>
    <div class="form-group">
      <label for="grade">Grade:</label>
      <input name="grade" type="text" class="form-control" id="grade" placeholder="Enter Grade">
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
  </form>
</div>

</body>
</html>
Check the form in web browser ("http://localhost:3000/user_info.html"), it will look something like below image.


6. Now Let's write the API to handle the form data
If the simple web form is rendering properly on your web browser you can continue with this step. We have 3 fields in that form including email, name and grade. The form action is set to "save_user", so once the form is submitted it will send the data to save_user API. So in order to handle this form data we will need to add a route in our server.js with the name save_user.

Add following two lines at the end of initialization section of server.js.
var bodyParser = require('body-parser');
var urlencodeParser = bodyParser.urlencoded({ extended:false});
Add following route after our default route in which we have displayed the message "my first node server".
app.post('/save_user', urlencodeParser, function(req, res){
   var response = {
    email:req.body.email,
    name:req.body.name,
    grade:req.body.grade
   }
   res.end(JSON.stringify(response));
});
In above step, we have created new end point with name "save_user" using app.post method. If you check the difference between our first & second route you can see there is a change of the method. In first route we have used app.get and in this route we have used app.post because we are expecting some post data as an input for this API to work. This is really straightforward and simple.

In this API we have created a JavaScript variable "response" and simply creating the object by taking the post data with the help of reference like "req.body.email". We are able to get the POSt data because of the module included in initialization section "body-parser". We can check this module in details later to more about its functions.

We are using "res.end(JSON.stringify(response));" to generate the response of the API. Now you can run the form "http://localhost:3000/user_info.html" in browser and fill all the data and hit enter. This will hit our save_user API and you can see output something similar to below image.

If you are able to see similar screen then congrats you have successfully implemented first cut of your first web service. Till now we have just taken the POST data and returning it in JSON format but what we actually need is to insert these records in database. Usually, the APIs core responsibility is to insert something into the database and to retrieve the data from database, wrap it with the business logic and return in the form of JSON data. So let's add that functionality to pour API to make it complete. For that we need to have MongoDB server, so let's go to our next step and create a new database.

7. Install MongoDB and create a database
Check if its already installed or not by using following command.
mongod --version
If it's giving you error then go ahead and install it using following commands
sudo apt-get update
sudo apt-get install -y mongodb-org
Once this is done, start the database server by using following command
sudo service mongod start

Now let's go to mongo shell (#mongo) & let's create database & users for your database.
use user_info  #this wil create your database with name user_info

8. Lets connect to database using ExpressJS and save the data.
We have already written the API save_user which is currently just fetching the data from POST. But the save_user API is suppose to do more than this, yes we need to connect to the database and save the information coming from the web form to the database.

1. Open the file "user_info/config/database.js" created in step 3.
This file is nothing but the configuration file for our database. We have to specify the MongoDB connection string in following format.
mongodb://[username:password@]host[:port][/[database_name]

module.exports = {
    remoteUrl : 'mongodb://admin:admin@localhost:27017/userInfo',
    localUrl: 'mongodb://admin:admin@localhost:27017/userInfo'
};

2.Load the config file in server.js
The database configuration file created in above step needs to be included in server.js to make use of the connection string. As we have created it as a module we can use require() method to include the database and make it available for ExpressJS. Add following line at the bottom of the initialization section of server.js
var database = require('./config/database');   // load the database config

3.Learn to connect MongoDB using mongoose
We have successfully imported the database module in step above. Now we will see how can we use module "mongoose" to connect to the mondoDB database.
Copy following lines and paste them below the require statement of database. The first line we are including the module mongoose and in second line we are making a connection to the database using localUrl. Notice that we have two different connection strings in database.js one is for local setup and one is for remoteUrl, for now you can also keep only one to complete the tutorial.
var mongoose = require('mongoose'); 
mongoose.connect(database.localUrl);  

4. Lets create "info" model (you can change this name)
Before we start writing the code to save the form data in to the database we will first need to define the model for the form. So lets quickly create new file "info.js" under "user_info/model" and write below model object in that file. Ths object is self explanatory.
var mongoose = require('mongoose');

module.exports = mongoose.model('Info', {
    name: {
        type: String,
        default: ''
    },
    email: {
        type: String,
        default: ''
    },
    grade: {
        type: String,
        default: ''
    }
});
Once this is done, we will need to include info model in our server.js file. So copy following command and paste at end of the initialization section.
var Info = require('./models/info');

5. Let's save the data into database by rewriting save_user route
As we have our data model ready we can simply replace the save_user route from server.js with the code below. Before copying the code please notice that I have just added one code block "Info.create()" and the POST data is sent to this method. This code block itself does everything and the form data gets stored in the database. We will write one more API after this to check the inserted records.
app.post('/save_user', urlencodeParser, function(req, res){
   var response = {
    email:req.body.email,
    name:req.body.name,
    grade:req.body.grade
   }
   res.end(JSON.stringify(response));

   Info.create({
            email:req.body.email,
      name:req.body.name,
      grade:req.body.grade
        }, function (err, todo) {
            if (err)
                res.send(err);
        });

});

6. Fetch the database from MongoDB using ExpressJS and Node
Once the above step is complete your app to save the database into the database using node and ExpressJS is done, but we will add one more API to check all the data inserted with the help of this API. So let's call it as "all_info" API.
copy the code below and put it at the end of routes section of server.js. This is nothing but a new API "all_info" which makes use of info model and find the method which returns all the records of that model.
app.get('/all_info', urlencodeParser, function(req, res){
   
   Info.find(function(err, infos){
    if(err)
     res.send(err)

    res.json(infos);
   });

});

9. Run and test your first MEAN stack application.
  • Restart your node server. ( you can hit control + C to close current session and then again run "node server.js")
  • Open web browser and hit URL "http://localhost:3000/user_info.html"
  • Enter some data in webform and hit submit.
  • This step will save form data in database.
  • Open web browser and hit URL "http://localhost:3000/all_info"
  • This will show you all the data from database, your screen will look something like below screenshot.

Remember above are just APIs, who's job is to return JSON data. You can later on create views and call these API. I will try to cover the view integration in my next post.
Monday, January 30, 2017

Basic SEO checklist before launching your new website

Take a pause. Is your website ready? ask yourself again. Technically it might be, but are you really sure that it's optimized and ready with SEO as well? OK, so now if you are not sure then this article is very important for you and your business. I have worked on more than 15 different business models and optimized 100 plus websites to improve their search engine listings. While working on such a huge number of projects, I realized that there are some very very common things which we need to do irrespective of their business model or type of website. So this is the list of very basic and important things which we should integrate before launching your new business website.


When it comes to SEO, the first thing to learn is, don't be impatient, good things take time. . It's very very difficult to recover from SEO penalty. If search engine ranks your website lower, then bringing it up is a challenge. So while launching your new website it's always better and safest way to check it for common things first and not to rush to make it live. So let's go over the pre-launch SEO checklist & make your website ready for launch.

1. Make sure you have prepared a perfect robots.txt

What is robots.txt? - Many time there are few pages/directories which we don't want any search engine to crawl/index. e.g. some backup files, control panel directories, basically anything which you don't want to appear in search engine result pages.
Why we should do this? - Let search engines have only the good and optimised pages of your website to decide it's ranking. If there are such unnecessary and more number of pages then overall website rankings will be calculated from all these pages, so let only few & important pages be indexed. We also have to control the traffic of search engine crawlers to our website because we don't want our web server to keep serving to web crawlers mainly for the pages which are not important.

How to allow full access in robots.txt file
Following block will allow all crawlers(User-agent: *) to access all files and folders from your web server.
User-agent: *
Disallow:
   
How to block full website in robots.txt file
Following lines will block all crawlers to access your web site, so nothing will appear in search engine result pages.
User-agent: *
Disallow: /
   
How to block a multiple folders in robots.txt file
User-agent: *
Disallow: /folder_name1/
Disallow: /folder_name2/
   
How to block a pages in robots.txt file
User-agent: *
Disallow: /filename.php
   
How to block all bots except google, Yahoo and Bing
User-agent: *
Disallow: /

User-agent: Googlebot
Allow: /

User-agent: Yahoo-slurp
Disallow: 

User-agent: Msnbot
Disallow:
   
How to add sitemap.xml in robots.txt file
Its always a better practice to have a xml sitemap for your website. Its not mandatory but its good practice. Check the below code to add the sitemap to robots.txt.
http://www.dhaneshmane.com/sitemap.xml
   
Following is the URL of my robots.txt, you can have a look at it while making one for your domain.
http://www.dhaneshmane.com/robots.txt
   
You should always test your robots.txt file with the tester provided by Google.
Click here to test your robots.txt file.

2. Non www to www redirect in .htaccess

If you are having 2 different URLs on your website with absolutely same contents then search engines consider it as duplicate content issue. As a best SEO practice, we should always avoid such issues.
Your website's home page can be open with 2 URLs, www.domainname.com and domainname.com. Both of these URLs point to the home page of the website so it will be considered as the duplicate content issue. I usually keep 301 permanent redirect from non-www to www using .htaccess file in apache web server. You can copy following code in your .htaccess file.
RewriteEngine on
RewriteCond %{HTTP_HOST} ^dhaneshmane.com [NC]
RewriteRule ^(.*)$ http://www.dhaneshmane.com/$1 [L,R=301,NC]

3. Redirect index.php to root in htaccess

This is one more URL which can create the duplicate content issue with domain root. Your domain root (w.g.www.dhaneshmane.com) is always pointing to index pages like index.php or index.html so this is another instance where we can have the duplicate content issue. In this case, we do a 301 permanent redirect of index.php to website root. Just copy the lines in below box and paste in your htaccess file.
RewriteRule ^(.*)index\.(php|html?)$ /$1 [R=301,NC,L]
Above rewrite rule will redirect index.html / php to it's root with server response code as 301. the NC flag at the end will make it case case-insensitive, so this is the safest way to achieve this.

4.Content is god - 300 plus words per page is very important

SEO is much difficult these days as most of the old SEO strategies began to fail. Google and other search engines updating their algorithm very frequently and scrapping all old techniques to promote your website.

In order to make a successful website, you have to have a very powerful content writer. Make sure each page is having more than 300 words. Make sure all pages have their unique identity & did not conflict with any other page. Try to generate original contents and do not copy from any other website, if you think this process will take time then don't worry. It's always better to make a perfect website and then launch it rather than launching and later thinking about optimizing.

5. Optimized & unique meta data for every page

I am sure everyone know what a meta data is and how important it is for the website. One important thing to remember while preparing the meta data for your website is, every page must have unique set of keywords and description.
  • Make sure you have proper contents for each keyword you are planning to use in meta keyword.
  • While choosing keywords don't forget long tail keywords
  • Link keywords in contents to respective website page if available.


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. Lets learn with the following example.

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.

Next > Highlight data points on mouseover

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, 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. So lets learn how to dump mysql database with the data from CSV file with an example.

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


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

Sunday, December 25, 2016

Semantic way of giving caption to an image in HTML5

Whenever there is an image on our website, it's always a great idea to have a relevant and appropriate image caption. If we check websites where images play an important role as a part of the main content, then image caption is a compulsory element for such websites.

News websites, magazine sites, modeling, art and photography related websites have lots of image contents. An Image caption is equally important element for such websites to help users understand the details of image very quickly.

Difference between <img> & <figure> elements


So how do we do it in HTML?
An old & unstructured way of giving a caption to an image does not have any disadvantages as such but it was not a semantic way. Following is one of the old ways of creating image element with a caption. Developers usually give some class to an image and DIV tag so it will get proper alignment and finally appears as an image caption.
  <img src="imagename.jpg" class="classname" />
  <div>This is image caption</div>

Improved & Semantic way to give image caption in HTML5.
So is there any standard way to write these elements to your browser? Yes, HTML5 is the answer to your question. All of us know that HTML5 have really come up with lots of new tags and features, but it's still not completely adapted and many of its newly added elements and attributes are not used. <figure> - Yes I am talking about this newly added element which is used for adding captions to images in an semantic way. So lets take a look at new way of writing this element.
 <figure>
    <img src="imagename.jpg" class="someClass" />
    <figcaption>
        <p>This is an image caption in Semantic way :)</p>
    </figcaption>
 </figure>

The sameple above shows the use of newly created HTML5 elements <figure> & <figcaption>. Use of these two elements is collectively called as semantic way of integrating image captions. You can use above code sample in your next projects.
Happy HTML5:)
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.

Tuesday, December 13, 2016

Virtual Reality by Mi @ unbelievable coast 999

Yes readers, I know that its really a jaw dropping price when you are talking about Virtual Reality. XIAOMI(Mi) have recently launched their new stunning product in the market of Virtual Reality. We all know that Xiomi is very famous technology brand because of the quality of their product at really affordable prices. This time they hit the VR market by introducing a cool new Mi VR play at really cheap price of Rs 999.



Mi VR comes with comfortable size 11.5 cm (4.7) x 14.5 cm and gives you an opportunity to explore the whole world of VR which is really very exciting. It also supports Google Cardboard Camera. So many more things coming along with this fun box , go to Mi website and have a look for more specifications.
Monday, March 28, 2016

Red Umbrella - Couple in Rain painting

and one more version of my Red Umbrella theme is here. After lots of sculpturing in my last project I decided to spend some time back to canvas painting over last weekend. I always wanted to add some more beautiful and romantic couple paintings to my Red Umbrella theme. Luckily there was a perfect size canvas board in my drawer, so I started working on it.


This is not only normal acrylic painting but I am learning pop art with this type of painting. I am not very good at it but yes I like spending time to learn new techniques. So have a look at it.

Red Umbrella couple painting version 2

I have transferred newspaper on canvas board first. Let it dry and then I did all the drawing work with pencil. After that only job left was painting a black n red color and rain effect.
Sunday, March 27, 2016

Moonlight Love - Boy proposing girl on moon portrayed on canvas

And here is my new mix media painting, I call it "Moonlight Love". I have used very less media elements, but this really looks very beautiful and based on creative idea. I really enjoyed making this painting. This picture portray a boy proposing girl sitting on moon. Blue background with moonlight effect with lots of stars makes this picture a very romantic gift for your partner.





Boy and Girl gives 3D effect because its created separately on different paper. I have done it with sketch pen first and then its added to main canvas board. This unique idea makes it feel like a 3D painting.

Elements Used.

  1. Sketch Pen 
  2. Cardboard paper to make 3D effect 
  3. Canvas Board Acrylic Colors
  4. Color Varnish 
  5. Heart shape stickers
Thursday, March 17, 2016

Shivaji Maharaj Rajmudra Sculpture

I always like to do something new and creative in my art projects. Last time I started working on mix media painting and I successfully created beautiful painting of lord Buddha. This time I decided to do something new and I decided to create sculpture of || Rajmudra of Shivaji Maharaj ||.


Shivaji Maharaj Rajmudra

I have used 16x20 inch size of canvas board for this sculpture. It took almost 45 hours for me to complete this Rajmudra. It was really a fun working on this project. I first created a stencil of this Rajmudra then with the help of this stencil I finished my drawing on the canvas board. I always used canvas board for only painting purpose this is the first time I have used it to make sculpture.

Rajmudra with copper and black color effect


Embossed lettering effect with copper and black color gives it a perfect look.
scroll down to bottom of the page to understand the meaning of " || Shivaji Maharaj Rajmudra || ".
Embossed letter effect

mudra in plain copper color

Rajmudra with black shadow effect


   || Shivaji Maharaj Rajmudra with frame ||

Those who don't know history of this Mudra must be wondering what exactly is written on this sculpture. So let me help you all with the real meaning of this Murda.

(English) - The glory of this Mudra of Shahaji’s son Shivaji (Maharaj ) will grow like the first day moon. It will be worshiped by the world & it will shine only for well being of people.

(Sanskrit) - “प्रतिपच्चंद्रलेखेव वर्धिष्णुर्विश्ववंदिता शाहसुनोः शिवस्यैषा मुद्रा भद्राय राजते।”

(Marathi) -   प्रतिपदेचा चन्द्र जसा वाढत जातो, आणि सरे विश्व त्याला जसे वंदन करते, तशीच तशीच ही मुद्रा व् तिचा लौकिक वाढत जाईल…..!


"Shivaji Maharaj Rajmudra" is the official stamp of Shivaji Maharaj which was used on his official letters, Orders etc. Rajmudra was also "Royal coin" during the reign of ‘Chatrapati Shivaji Maharaj’