Scatter Plot Using D3JS

Introduction

 
This article is all about how to use your data from various resources and generate some charts depending on your application requirements. In this article, I am using simple JSON data and D3JS for creating charts. 
 
Outlines
  • Overview
  • Problem-Solution
  • Demo
    • HTML Snippet
    • CSS Snippet
    • JavaScript Snippet
    • Output
       
  • Reference Examples
  • Summary
Overview
 
D3JS is a JavaScript library for data visualization mostly. From data visualization, I mean data and information representation in the forms of charts (Bar, Pie, Line, Area, Scatter, Histogram, Donut and so on). D3JS is widely used for its well-defined functionality and its work flow simplicity. In D3JS we need to use a few properties related to the respective chart and the work is over.
 
One of the major advantages of D3JS is that you don't need to give too much to go through it, since it is a part of JavaScript and uses a similar operation mode and functions like it. So if you are familiar with JavaScript then it's for you.
 
What you need to do is simply embed your JavaScript in your Simple HTML code and you're done. For decoration and formatting, you can use CSS and its related components.
 
I hope this much of an introduction to D3JS will be enough at this level. I'll try to write a basic introductory article on D3JS containing features, properties, application areas, advantages, scope and so on.
 
For more info, please visit my previous articles related to D3.JS. Here are the links for those base articles:
 
http://www.c-sharpcorner.com/UploadFile/2072a9/diving-into-d3-js/
http://www.c-sharpcorner.com/UploadFile/2072a9/creating-bar-chart-from-d3js-using-csv-data/
 
Problem-Solution
 
That diagram is self-explanatory, like why we need D3.JS and what the problems are and all.
 
 
Demo 
 
In this demo of a scatter plot, I'll show you how easily you can generate scatter plots using D3.JS. In this demo we are using only:
  • HTML Snippet
  • CSS Snippet
  • JavaScript
Visualized data
 
HTML Snippet 
 
In your HTML snippet you need to only mention resource file links and CSS file links with structure, as in the following:
  1. <Script src="http://d3js.org/d3.v3.js" type="text/javasript"/>    
  2. <link rel =”” href=”Style.css” type=””/> 
CSS Snippet 
  1. body     
  2. {    
  3.     font-family:"Helvetica Neue";    
  4.     color#686765;    
  5. }    
  6.     
  7. .name     
  8. {    
  9.     float:right;    
  10.     color:#27aae1;    
  11. }    
  12.     
  13. .axis     
  14. {    
  15.     fill: none;    
  16.     stroke: #AAA;    
  17.     stroke-width1px;    
  18. }    
  19.     
  20. text    
  21. {    
  22.     stroke: none;    
  23.     fill: #666666;    
  24.     font-size: .6em;    
  25.     font-family:"Helvetica Neue"    
  26. }    
  27.     
  28. .label     
  29. {    
  30.     fill: #414241;    
  31. }    
  32.     
  33. .node     
  34. {    
  35.     cursor:pointer;    
  36. }    
  37.     
  38. .dot     
  39. {    
  40.     opacity: .7;    
  41.     cursorpointer;    
  42. }   
JavaScript and D3.JS Snippet
 
Here is a JavaScript snippet for plotting a chart. I divided this snippet into two parts. The first portion includes JSON data and the second part includes a sample D3.JS code snippet.
 
This is sample JSON data in blocks. For further information related to JSON data and JSON, such as how to generate JSON data from SQL Tabular data, XML data source, JSON description, and many more things, please visit my previous article:
 
http://www.c-sharpcorner.com/UploadFile/2072a9/data-parsing-sql-to-json/
 
So here we go.
 
// Sample JSON data
  1. var Languages = [    
  2. {    
  3.     "name""HTML5/CSS3",    
  4.     "Vote"65,    
  5.     "rating"2    
  6. },    
  7. {    
  8.     "name""JavaScript",     
  9.     "Vote"60,    
  10.     "rating"3    
  11. },    
  12. {    
  13.     "name""Java",     
  14.     "Vote"60,    
  15.     "rating"4    
  16. },     
  17. {    
  18.     "name""C#",     
  19.     "Vote"80,    
  20.     "rating"1    
  21. },     
  22. {    
  23.     "name""SQL",    
  24.     "Vote"55,    
  25.     "rating"5    
  26. }, ];   
// D3.JS Code Snippet
  1. // Calling the method below    
  2.  showScatterPlot(Languages);    
  3.      
  4.  function showScatterPlot(data)     
  5.  {    
  6.      // Spacing Around     
  7.      var margins =    
  8.      {    
  9.          "left": 40,    
  10.          "right": 30,    
  11.          "top": 30,    
  12.          "bottom": 30    
  13.      };    
  14.      
  15.      var width = 500;    
  16.      var height = 500;    
  17.      
  18.      // This will be our colour scale. An Ordinal scale.    
  19.      var colors = d3.scale.category10();    
  20.      
  21.      // Adding the SVG component to the scatter-load div    
  22.      var svg = d3.select("#scatter-load").append("svg").attr("width", width).attr("height", height).append("g")    
  23.      .attr("transform""translate(" + margins.left + "," + margins.top + ")");    
  24.      
  25.      // Setting the scale that we're using for the X axis.     
  26.      // Domain define the min and max variables to show. In this case, it's the min and max Votes of items.    
  27.      // this is made a compact piece of code due to d3.extent which gives back the max and min of the Vote variable within the dataset    
  28.      var x = d3.scale.linear()    
  29.      .domain(d3.extent(data, function (d)     
  30.      {    
  31.          return d.Vote;    
  32.      }))    
  33.      
  34.      // Range maps the domain to values from 0 to the width minus the left and right margins (used to space out the visualization)    
  35.      .range([0, width - margins.left - margins.right]);    
  36.      
  37.      // Scalling for the y axis but maps from the rating variable to the height to 0.     
  38.      var y = d3.scale.linear()    
  39.      .domain(d3.extent(data, function (d)    
  40.      {    
  41.          return d.rating;    
  42.      }))    
  43.      
  44.      // Note that height goes first due to the weird SVG coordinate system    
  45.      .range([height - margins.top - margins.bottom, 0]);    
  46.      
  47.      // Adding the axes SVG component. At this point, this is just a placeholder. The actual axis will be added in a bit    
  48.      svg.append("g").attr("class""x axis").attr("transform""translate(0," + y.range()[0] + ")");    
  49.      svg.append("g").attr("class""y axis");    
  50.      
  51.      // X axis label. Nothing too special to see here.    
  52.      svg.append("text")    
  53.      .attr("fill""#414241")    
  54.      .attr("text-anchor""end")    
  55.      .attr("x", width / 2)    
  56.      .attr("y", height - 35)    
  57.      .text("Votes");    
  58.      
  59.      
  60.      // Actual definition of our x and y axes. The orientation refers to where the labels appear - for the x axis, below or above the line, and for the y axis, left or right of the line. Tick padding refers to how much space between the tick and the label. There are other parameters too - see https://github.com/mbostock/d3/wiki/SVG-Axes for more information    
  61.  var xAxis = d3.svg.axis().scale(x).orient("bottom").tickPadding(2);    
  62.  var yAxis = d3.svg.axis().scale(y).orient("left").tickPadding(2);    
  63.      
  64.      // Selecting the axis we created a few lines earlier. See how we select the axis item. in our svg we appended a g element with a x/y and axis class. To pull that back up, we do this svg select, then 'call' the appropriate axis object for rendering.     
  65.      svg.selectAll("g.y.axis").call(yAxis);    
  66.      svg.selectAll("g.x.axis").call(xAxis);    
  67.      
  68.      // Now, we can get down to the data part, and drawing stuff. We are telling D3 that all nodes (g elements with class node) will have data attached to them. The 'key' we use (to let D3 know the uniqueness of items) will be the name. Not usually a great key, but fine for this example.    
  69.      var chocolate = svg.selectAll("g.node").data(data, function (d)     
  70.      {    
  71.          return d.name;    
  72.      });    
  73.      
  74.      // We 'enter' the data, making the SVG group (to contain a circle and text) with a class node. This corresponds with what we told the data it should be above.    
  75.      
  76.      var chocolateGroup = chocolate.enter().append("g").attr("class""node")    
  77.      
  78.      // this is how we set the position of the items. Translate is an incredibly useful function for rotating and positioning items     
  79.      .attr('transform'function (d)     
  80.      {    
  81.          return "translate(" + x(d.Vote) + "," + y(d.rating) + ")";    
  82.      });    
  83.      
  84.      // Adding our first graphics element! A circle!     
  85.      chocolateGroup.append("circle")    
  86.      .attr("r", 5)    
  87.      .attr("class""dot")    
  88.      .style("fill"function (d)    
  89.      {    
  90.          // remember the ordinal scales?     
  91.          // We use the colors scale to get a colour for our votes. Now each node will be coloured    
  92.          // by votes to the languages.     
  93.          return colors(d.manufacturer);    
  94.      });    
  95.      
  96.      // Adding some text, so we can see what each item is.    
  97.      chocolateGroup.append("text")    
  98.      .style("text-anchor""middle")    
  99.      .attr("dy", -10)    
  100.      .text(function (d)    
  101.      {    
  102.          // this shouldn't be a surprising statement.    
  103.          return d.name;    
  104.      });    
  105.  }    
 Output
 
Output Graph
 
Reference Examples
 
For a sample example of generating a bar chart using CSV data, you can go through my previous article that explains it all, at:
 
http://www.c-sharpcorner.com/UploadFile/2072a9/creating-bar-chart-from-d3js-using-csv-data/
 

Summary

 
I hope you now have a basic understanding of creating a chart for data visualization using D3.JS. it's simple and reusable. For more details or tutorials you can visit its official website that contains the detailed procedure and a description of creating various sorts of charts.
 
Meanwhile, if you experience any problem creating charts or learning D3.Js then feel free to ping me or message me.
 
In the next part of this series I'll try to present some more interesting things, until then #KeepCoding and Enjoy.


Similar Articles