Tutorial #5 Dive into DC.JS a JavaScript Library - Scatter Plot

in utopian-io •  7 years ago  (edited)

What Will I Learn?

  • Scatter Plot in dc.js
  • Multiple Scatter Plot
  • Scatter Plot Brushing

Requirements

Write here a bullet list of the requirements for the user in order to follow this tutorial.

  • Our Previous dc.js tutorials
  • Basics of HTML and CSS
  • Intermediate level JavaScript
  • Statistical Data

Difficulty

  • Intermediate

Tutorial Contents

  • What is Scatter Plot?
  • Build working environment
  • Build Scatter Plot
    • Simple Scatter Plot
    • Multiple Scatter Plot
    • Scatter Plot Brushing
What is Scatter Plot?

Scatter Plot also known as Scatter Graph, Scatter diagram, Scatter Chart and Scattergram - is a kind of mathematical diagram in which we visualize the data with the help of different data points. Each data point has the value of one variable which represents its position on x-axis and the other variable value represents its position on y-axis. A scatter plot can be used either when one continuous variable that is under the control of the experimenter and the other depends on it or when both continuous variables are independent.

Build working environment

If you've read our previous tutorials then you know how set up a working environment for dc.js and how to connect libraries in our files. Here in this tutorial we'll again use the json data that we continuously using in our previous tutorials, So, we copy and paste the code in our files.

DOCTYPE html>
<html lang="EN">
    <head>
      <meta charset="utf-8">
      <title>Scatter Plot</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" />
    </head>
    <body>
        <h1>Scatter Plot: Tip againt Payment</h1>
        <div id="scatterPlot" ></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"}
        ];

          var facts = crossfilter(paymentsRecord);
        </script>

    </body>
</html>

Build Scatter Plot

Above we create working environment, place the json data and feed it to crossfilter.js.

Simple Scatter Plot

Today, we are going to develop scatter chart of tip against payment. As you can see in the above code we didn't create dimension and relevant group, here for this tutorial the dimension and group will be little different from our previous tutorials.

var scatterDimension = facts.dimension(function(d){ return [d.total, d.tip]; }); Here we created dimension of tip and total payment.

var scatterGroup = scatterDimension.group(); and then group them.

Once we done with our data related work, now we'll move to our scatter plot. Same like the other charts in the dc.js create the object of scatterPlot class and pass it the ID of the div, set it width and height them dimension and group . Here one thing you've to do more is to customize the x-axis

var scatter = dc.scatterPlot("#scatterPlot"); 
          .width(1024)
          .height(200)
          .dimension(scatterDimension)
          .group(scatterGroup)
 .x(d3.scale.linear().domain([0,350])); //customize the a-axis 
        scatter.yAxis().ticks(5);
        dc.renderAll();

Boom, our scatter plot is create, but with not a good looking interface. See the out put

scatter-plot-1.JPG

You can see our data points are really small, and overall graph not looking great. Don't you worry, scatterPlot class itself come up with a lot of interesting methods that'll help you make you scatter plot interesting to see.

To increase the size of the data points use this method .symbolSize(20). Here we pass the argument 20 you can set any size by just passing argument value.
scatter-plot-2.JPG

You can see the size is increases but the some data points are behind the line, use this method .clipPadding(20) , This method get or set the padding in pixels for the clip path.

scatter-plot-3.JPG

Now it looks little better, You can also change the shape of the symbol, for this we use .symbol() by default the shape is circle, you can pass argument shape name to change the shape of data points('symbols'). As if we pass "square" parameter .symbol('square'), the shape of data points turn into square.

scatter-plot-4.JPG

The interest function we like in scatterplot class is, the color of the data will change to the value of the data point. For this you have to use these methods


          .colorAccessor(function(d){ return d.value; })
          .colors(d3.scale.category20b())

You can see the data point will be of different color, on the base of value of data point.

scatter-plot-5.JPG

Here are the other methods of scatterPlot class with their description, you can try these by yourself.

.emptyColor() // when the group is empty this methods sets/gets the color for the symbols.
.emptyOpacity() //
.nonemptyOpacity()//
.existenceAccessor([accessor])// 
.customSymbol([customSymbol])// you can generate symbol, by default the class use d3.svg.symbol() to generate symbols
.emptySize([emptySize]) // size while empty 
// There are a lot other you can check the documentation of the dc.js

Demo

Multiple Scatter Plot

To create multiple scatter chart we'll use the compositeChart class, If you are not familiar with this class them please read our tutorial #4. Here we uses CompositeChart Class that help us in create multiple scatterPlot. You can create as my as you want. See the code

var scatterDimension = facts.dimension(function(d){ return [d.total, d.tip]; });
          var scatterGroup = scatterDimension.group();

          var lineDimension = facts.dimension(function (d){ return d.total;});
          var lineGroup = lineDimension.group().reduceSum(function(d){ return d.tip; });

          var scatter = dc.compositeChart("#scatterPlot")
          .width(1024)
          .height(200)
          .margins({top:10,bottom:30,right:20,left:50})
          .dimension(scatterDimension)
          .legend(dc.legend().x(70).y(10).itemHeight(10).gap(5))
          .brushOn(false)
          .compose([
              dc.scatterPlot('scatter')
                  .group(scatterGroup, "Red Group")
                  .symbolSize(20)
                  .clipPadding(20)
                  .symbol('square')
                  .colors("red"),

              dc.scatterPlot('scatter')
                  .group(scatterGroup, "Blue Group")
                  .symbolSize(20)
                  .valueAccessor(function (d) { return d.key[0] + 200; }) // change the value for 2nd graph
                  .clipPadding(20)
                  .symbol('cross')
                  .colors("blue"),
             dc.lineChart('scatter')
                  .dimension(lineDimension)
                  .group(lineGroup, "Line Group")

          ])
          .x(d3.scale.linear().domain([0,350]));
        scatter.yAxis().ticks(5);
        dc.renderAll();

Output:
scatter-plot-6.JPG

Demo

Scatter Plot Brushing

Here we are going to show you the really interesting scatter chart. We'll build two chart, when you brush the each data point of the one chart you'll see the points filtered on the other.

For this we have to create the two charts this means we need two dimensions and two groups, a group for each dimension.

We created here these dimensions and groups . These dimension should be in this way first dimension [x,y] and 2nd dimension [y,z].

//First dimension 
var scatterDimension1 = facts.dimension(function(d){ return [d.total, d.tip]; });
        var scatterGroup1 = scatterDimension1.group();

// 2nd dimension
        var scatterDimension2 = facts.dimension(function(d){ return [d.tip, d.quantity] });
        var scatterGroup2 = scatterDimension2.group();

After dimension created, you just have to create two scattered chart as we created above in first example. see the code.

//First Chart
        var scatter1 = dc.scatterPlot("#scatterPlot1")
        .width(1020)
        .height(250)
        .margins({top:10,bottom:30,right:20,left:50})
        .dimension(scatterDimension1)
        .group(scatterGroup1)
        .symbolSize(15)
        .clipPadding(20)
        .x(d3.scale.linear().domain([0,350]));
      scatter1.yAxis().ticks(5);

//2nd Chart

      var scatter2 = dc.scatterPlot("#scatterPlot2")
      .width(1020)
      .height(400)
      .margins({top:20,bottom:30,right:20,left:100})
      .dimension(scatterDimension2)
      .group(scatterGroup2)
      .symbolSize(15)
      //.symbol("square")
      .clipPadding(20)
      .x(d3.scale.linear().domain([0,350]));
    scatter2.yAxis().ticks(5);

      dc.renderAll();

output

scatter_plot.gif

You can see when We brush the data point of the one chart it filters the other chart.

Demo

Curriculum

Place here a list of related tutorials you have already shared on Utopian that make up a Course Curriculum, if applicable.



Posted on Utopian.io - Rewarding Open Source Contributors

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Hey @faad I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x