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.

Self Explanation

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.

<script src="http://d3js.org/d3.v3.js" type="text/javascript"></script>
<link rel="stylesheet" href="Style.css" type="text/css"/>

CSS Snippet

body {
    font-family: "Helvetica Neue";
    color: #686765;
}
.name {
    float: right;
    color: #27aae1;
}
.axis {
    fill: none;
    stroke: #AAA;
    stroke-width: 1px;
}
text {
    stroke: none;
    fill: #666666;
    font-size: .6em;
    font-family: "Helvetica Neue";
}
.label {
    fill: #414241;
}
.node {
    cursor: pointer;
}
.dot {
    opacity: .7;
    cursor: pointer;
}

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

var Languages = [
    {
        "name": "HTML5/CSS3",
        "Vote": 65,
        "rating": 2
    },
    {
        "name": "JavaScript",
        "Vote": 60,
        "rating": 3
    },
    {
        "name": "Java",
        "Vote": 60,
        "rating": 4
    },
    {
        "name": "C#",
        "Vote": 80,
        "rating": 1
    },
    {
        "name": "SQL",
        "Vote": 55,
        "rating": 5
    }
];

// D3.JS Code Snippet

// Calling the method below
showScatterPlot(Languages);

function showScatterPlot(data) {
    // Spacing Around
    var margins = {
        "left": 40,
        "right": 30,
        "top": 30,
        "bottom": 30
    };

    var width = 500;
    var height = 500;

    // This will be our colour scale. An Ordinal scale.
    var colors = d3.scale.category10();

    // Adding the SVG component to the scatter-load div
    var svg = d3.select("#scatter-load")
        .append("svg")
        .attr("width", width)
        .attr("height", height)
        .append("g")
        .attr("transform", "translate(" + margins.left + "," + margins.top + ")");

    // Setting the scale that we're using for the X axis.
    // Domain defines the min and max variables to show. In this case, it's the min and max Votes of items.
    // 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
    var x = d3.scale.linear()
        .domain(d3.extent(data, function (d) {
            return d.Vote;
        }))
        // Range maps the domain to values from 0 to the width minus the left and right margins (used to space out the visualization)
        .range([0, width - margins.left - margins.right]);

    // Scaling for the y axis but maps from the rating variable to the height to 0.
    var y = d3.scale.linear()
        .domain(d3.extent(data, function (d) {
            return d.rating;
        }))
        // Note that height goes first due to the weird SVG coordinate system
        .range([height - margins.top - margins.bottom, 0]);

    // Adding the axes SVG component. At this point, this is just a placeholder. The actual axis will be added in a bit
    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + y.range()[0] + ")");
    svg.append("g").attr("class", "y axis");

    // X axis label. Nothing too special to see here.
    svg.append("text")
        .attr("fill", "#414241")
        .attr("text-anchor", "end")
        .attr("x", width / 2)
        .attr("y", height - 35)
        .text("Votes");

    // 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
    var xAxis = d3.svg.axis().scale(x).orient("bottom").tickPadding(2);
    var yAxis = d3.svg.axis().scale(y).orient("left").tickPadding(2);

    // 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 an x/y and axis class. To pull that back up, we do this SVG select, then 'call' the appropriate axis object for rendering.
    svg.selectAll("g.y.axis").call(yAxis);
    svg.selectAll("g.x.axis").call(xAxis);

    // 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.
    var chocolate = svg.selectAll("g.node")
        .data(data, function (d) {
            return d.name;
        });

    // 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.
    var chocolateGroup = chocolate.enter()
        .append("g")
        .attr("class", "node")
        // This is how we set the position of the items. Translate is an incredibly useful function for rotating and positioning items
        .attr('transform', function (d) {
            return "translate(" + x(d.Vote) + "," + y(d.rating) + ")";
        });

    // Adding our first graphics element! A circle!
    chocolateGroup.append("circle")
        .attr("r", 5)
        .attr("class", "dot")
        .style("fill", function (d) {
            // Remember the ordinal scales?
            // We use the colors scale to get a colour for our votes. Now each node will be coloured
            // by votes to the languages.
            return colors(d.manufacturer);
        });

    // Adding some text, so we can see what each item is.
    chocolateGroup.append("text")
        .style("text-anchor", "middle")
        .attr("dy", -10)
        .text(function (d) {
            // This shouldn't be a surprising statement.
            return d.name;
        });
}

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.