Tutorial #16 Dive into DC.JS a JavaScript Library - Link two Charts

in #utopian-io6 years ago (edited)

What Will I Learn?

  • Link the Charts in dc.js
  • How corssfilter.js help us to link the chart in dc.js

Requirements

  • Basics of HTML and CSS
  • JavaScript Essentials
  • crossfilter.js and d3.js
  • Understanding of Statistical Data

Difficulty

  • Intermediate

Tutorial Contents

  • Introduction
  • Create working environment
  • Link two chart together
    - Develop 1st Data Table
    - Develop 2st Pie Chart
Introduction

Here in this tutorial we are going to link two charts together. We'll use a data table and a bar chart for our tutorial and at the end we link them logically. When we click on each slice of the pie-chart the data table only shows the data related to that slice of the pie-chart.

link-charts.gif

Create Working Environment

First of all we'll create a working environment in order to use the dc.js library. To do this, open your text editor and create a file with name linkCharts.html and save it. After this, write code HTML code necessary to work with HTML file.

<!DOCTYPE html>
<html lang="EN">
    <head>
      <meta charset="utf-8">
      <title>Bar Chart</title>

    </head>
    <body>
    </body>
</html>

Now link your dc.js library to our files and the other libraries that are necessary to work with dc, crossfilter.js and d3.js


      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.1/d3.min.js"></script>
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/crossfilter/1.3.12/crossfilter.min.js"></script>
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/dc/2.1.9/dc.min.js"></script>
      <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/dc/2.1.9/dc.min.css" />
      <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

Her above we also link the bootstrap library for the styling our table.

Now write the code to give heading to our files and also write the code for the div and table and assign them IDs

<div id="main">
            <div id="pieChart"></div>
            <div id="table">
                <table id="dataTable" class="table table-hover" align="center"></table>
            </div>

We also do some styling to our table and pie chart div with the help of CSS. Add this code to your file


      <style>
      #main{
          width: 100%;
          padding: 10px;
          //border: 1px solid black;
      }
      div{
          overflow: auto;
          float:left;
      }
      td {
        border: 1px solid gainsboro;
      }
      h1{
          text-align: center;
      }

      #pieChart, #table{
          margin: 10px 10px 10px 20px;
          width:40%;
          //border: 1px solid black;
      }
      #dataTable {
          text-align: center;
          width:50%;
      }
      </style>

Now we just have to add the dummy data to start work with our charts.

        <script type="text/javascript">


          var paymentsRecord = [
          {date: "2011-11-14T16:17:54Z", quantity: 2, total: 190, tip: 100, type: "tab"},
          {date: "2011-11-14T16:20:19Z", quantity: 2, total: 190, tip: 100, type: "tab"},
          {date: "2011-11-14T16:28:54Z", quantity: 1, total: 300, tip: 200, type: "visa"},
          {date: "2011-11-14T16:30:43Z", quantity: 2, total: 90, tip: 0, type: "tab"},
          {date: "2011-11-14T16:48:46Z", quantity: 2, total: 90, tip: 0, type: "tab"},
          {date: "2011-11-14T16:53:41Z", quantity: 2, total: 90, tip: 0, type: "tab"},
          {date: "2011-11-14T16:54:06Z", quantity: 1, total: 100, tip: 0, type: "cash"},
          {date: "2011-11-14T16:58:03Z", quantity: 2, total: 90, tip: 0, type: "tab"},
          {date: "2011-11-14T17:07:21Z", quantity: 2, total: 90, tip: 0, type: "tab"},
          {date: "2011-11-14T17:22:59Z", quantity: 2, total: 90, tip: 0, type: "tab"},
          {date: "2011-11-14T17:25:45Z", quantity: 2, total: 200, tip: 0, type: "cash"},
          {date: "2011-11-14T17:29:52Z", quantity: 1, total: 200, tip: 100, type: "visa"}
        ];
        </script >

You can see in our data our date data is in string, we've to convert the string into date object. for this do this

    paymentsRecord.forEach(function(d){
        //console.log(typeof(d.date)); //check the type before it changes
        var orgDate = new Date(d.date); // changes the string date into origional date type
        d.date = orgDate; // Overwrite the String date with Original date type
        console.log(typeof(d.date)); //check the type after make change, you can see it converts into date object
    });


Link two chart together

Once you set up working environment, start developing our charts. For this first feed our dummy data to crossfilter.js. This will help us to create dimension and group our data.

          var facts = crossfilter(paymentsRecord);

Now create dimension and grouped the data. Here you know we are going to develop two charts. This is why we have to create dimension and group data for both charts.

          // Data Table
        var facts = crossfilter(paymentsRecord);
        var dimensionByDate = facts.dimension(function(d){ return d.date; });

        // Pie Chart by Payment Type

        var dimensionByType = facts.dimension(function(d){ return d.type; });
        var groupByType = dimensionByType.group();

Now we are going to create our first chart, first we create a Data Table, create the object of the dataTable class and pass it the id of the table that we created above. Also set the width and height.

        var dataTable = dc.dataTable("#dataTable")
              .width(1360)
              .height(300)

Now pass the dimension and group of the data to dataTable class that we created above .

              .dimension(dimensionByDate)
              .group(function(d){ return d.type; })

Now write all the other necessary methods require to create a data table. For the more details you ca check our data table tutorial.

        var dataTable = dc.dataTable("#dataTable")
              .width(1360)
              .height(300)
              .dimension(dimensionByDate)
              .showGroups(false)
              //.size(7)
              .group(function(d){ return d.type; })
              .columns([{label:'Time',format: function(d){ return d.date.getHours()+':'+d.date.getMinutes(); }},
                        'quantity',
                        'total',
                        'tip',
                        'type',

                    ])
              .sortBy(function(d){ return d.type; })
              .order(d3.descending);


Output:

linking-charts-1.JPG

Here you can see we've developed our data table.

Develop Pie Chart

Once we developed our data table now we'll move to pie, for this create the object of pieChart class and pass it the ID of the dive we created above for the pie chart. Also set the height and width of our pie chart.

        var barChart = dc.pieChart('#pieChart')
              //.width(1024)
              .height(250)

Now set the radius for the pie chart.

              .radius(150)

At the end pass the dimension and grouped data that we created from crossfilter.js for the pie chart.

              .dimension(dimensionByType)
              .group(groupByType)

At the end render the data

dc.renderAll();

Output:

linking-charts.JPG

If you filter the data table by clicking on the pie chart this will works perfectly fine for you. But we didn't do any thing to link these charts together. This works fine because dc.js automatically do it for use. The reason is that both charts working working the same data of crossfilter.js this is why dc.js link them together.

If you click on the slice of the cash you can only see the data related cash in the data table.

linking-charts-2.JPG

If you want to see the data of type "tab" then select the tab and off the other two.

linking-charts-3.JPG

You can also see the data for the 2 types at the same time.

linking-charts-4.JPG

Source Code:

<!DOCTYPE html>
<html lang="EN">
    <head>
      <meta charset="utf-8">
      <title>Link Charts</title>
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.1/d3.min.js"></script>
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/crossfilter/1.3.12/crossfilter.min.js"></script>
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/dc/2.1.9/dc.min.js"></script>
      <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/dc/2.1.9/dc.min.css" />
      <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

      <style>
      #main{
          width: 100%;
          padding: 10px;
          //border: 1px solid black;
      }
      div{
          overflow: auto;
          float:left;
      }
      td {
        border: 1px solid gainsboro;
      }
      h1{
          text-align: center;
      }

      #pieChart, #table{
          margin: 10px 10px 10px 20px;
          width:40%;
          //border: 1px solid black;
      }
      #dataTable {
          text-align: center;
          width:50%;
      }
      </style>
    </head>
    <body>
        <h1>Link Charts</h1>
        <div id="main">
            <div id="pieChart"></div>
            <div id="table">
                <table id="dataTable" class="table table-hover" align="center"></table>
            </div>
        </div>



        <script type="text/javascript">


          var paymentsRecord = [
          {date: "2011-11-14T16:17:54Z", quantity: 2, total: 190, tip: 100, type: "tab"},
          {date: "2011-11-14T16:20:19Z", quantity: 2, total: 190, tip: 100, type: "tab"},
          {date: "2011-11-14T16:28:54Z", quantity: 1, total: 300, tip: 200, type: "visa"},
          {date: "2011-11-14T16:30:43Z", quantity: 2, total: 90, tip: 0, type: "tab"},
          {date: "2011-11-14T16:48:46Z", quantity: 2, total: 90, tip: 0, type: "tab"},
          {date: "2011-11-14T16:53:41Z", quantity: 2, total: 90, tip: 0, type: "tab"},
          {date: "2011-11-14T16:54:06Z", quantity: 1, total: 100, tip: 0, type: "cash"},
          {date: "2011-11-14T16:58:03Z", quantity: 2, total: 90, tip: 0, type: "tab"},
          {date: "2011-11-14T17:07:21Z", quantity: 2, total: 90, tip: 0, type: "tab"},
          {date: "2011-11-14T17:22:59Z", quantity: 2, total: 90, tip: 0, type: "tab"},
          {date: "2011-11-14T17:25:45Z", quantity: 2, total: 200, tip: 0, type: "cash"},
          {date: "2011-11-14T17:29:52Z", quantity: 1, total: 200, tip: 100, type: "visa"}
        ];

        paymentsRecord.forEach(function(d){
            //console.log(typeof(d.date)); //check the type before it changes
            var orgDate = new Date(d.date); // changes the string date into origional date type
            d.date = orgDate; // Overwrite the String date with Original date type
            console.log(typeof(d.date)); //check the type after make change, you can see it converts into date object
        });

          var facts = crossfilter(paymentsRecord);

          // Data Table
        var facts = crossfilter(paymentsRecord);
        var dimensionByDate = facts.dimension(function(d){ return d.date; });

        // Pie Chart by Payment Type

        var dimensionByType = facts.dimension(function(d){ return d.type; });
        var groupByType = dimensionByType.group();


        var dataTable = dc.dataTable("#dataTable")
              .width(1360)
              .height(300)
              .dimension(dimensionByDate)
              .showGroups(false)
              //.size(7)
              .group(function(d){ return d.type; })
              .columns([{label:'Time',format: function(d){ return d.date.getHours()+':'+d.date.getMinutes(); }},
                        'quantity',
                        'total',
                        'tip',
                        'type',

                    ])
              .sortBy(function(d){ return d.type; })
              .order(d3.descending);



        var barChart = dc.pieChart('#pieChart')
              //.width(1024)
              .height(250)
              .radius(150)
              .dimension(dimensionByType)
              .group(groupByType)


        dc.renderAll();
          </script>
    </body>
</html>


Curriculum



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Coin Marketplace

STEEM 0.27
TRX 0.13
JST 0.032
BTC 64453.46
ETH 2971.59
USDT 1.00
SBD 3.59