Full path to create interactive visualization using D3.js

Contents

Introduction

If there is 2 Fundamental trends driving digital journalism, These would be:

  • More data about your customers is generated and captured.
  • Increased web penetration (or mobile) between customers and the need to tell data stories through the web.

This is where D3.js comes into play. D3.js has become the holy grail of interactive data visualization.

D3.js versus other alternatives

I believe that D3.js's popularity in the data science fraternity is out of sync with its true potential. The main reason is that you need a different skill set (as an example, HTML, CSS and JavaScript Knowledge) than most conventional tools for data science or machine learning. At the same time, there are readily available tools such as QlikView and Tableau that provide this feature.

Despite this, When you want dashboards / Personalized data stories delivered on the web at low cost, D3.js is one of the best tools available. And this is why we believe in creating this learning path.

Complete learning path to master d3.js

We've designed a beginner's learning path below. If you find it intimidating at first, do not worry, That's natural. But, if you promise to take your first step in D3.js, We promise that we will constantly help you overcome successive obstacles.

Note: This learning path has been designed assuming that you are a newbie to coding and web development languages (HTML / CSS and JavaScript). If you already know them, You can skip the corresponding sections.

What is D3.js?

Mike Bostock d3.jsData-driven documents (D3) is an open source JavaScript library that is used to create dynamic and interactive visualizations enabled in a modern web browser. Runs primarily with HTML, SVG, CSS and JavaScript. It was created by Mike Bostock, Computer scientist and data visualization specialist (In picture).

D3.js is extremely fast, responsive and also supports large datasets to create dynamic animations in web browsers. Collection of useful plugins and coding components makes d3 codes reusable.

Tip for beginners: If you are a beginner, can be confused between the Java programming language and the JavaScript scripting language. Son 2 Absolutely independent languages. Java is primarily used for software and application development, while JavaScript is used to create interactive web pages.

Paso 0: Motivation – Why learn D3.js?

I truly believe in the Golden Circle explained by Simon Sinek. He says, if you're starting with something, Start with “Why”?

Before starting your journey, must have an answer to this question:

Why should I learn D3.js?

O

How will D3.js?

Let me help you find his answer. View this Scott Murray talk, Author of Interactive Data Visualization for the Web, to understand the true power of creating web-enabled visualizations.

5 Real-world examples

This is essential. Let me show you some of the visualizations that are created with d3. You don't need to analyze these visualizations, but you get inspiration and a desire to create one.

  1. Strike carried out by the police in January 2012 in New York
  2. Markov Process
  3. Visual Introduction to Machine Learning
  4. Race Track Leads to Victory
  5. Connections between Oscar's contenders

I would strongly suggest that you spend some time on each of these pages interacting with the items on these pages. You will begin to see the power of what D3.js can offer you!

Scrolling More of 600 examples in D3.

Relevance of data visualization

If you have checked the examples above, I'm sure I don't need to stress the relevance of visualizing the data. You already know how well data can speak for itself. As a data scientist, Your real motive should be to explain the model to stakeholders. The real thing comes in presenting data to non-analytical stakeholders. They don't want numbers, but a beautifully crafted story with numbers. If you can perform this task with D3, Excellent work.

Paso 1: Learn the basics: HTML, CSS, SVG, Javascript

Clear Your Coding Basics First. If you have no prior coding knowledge, Start with HTML y CSS course of Codecademy. It's an interactive course and the best place to start.

Once you're done with HTML and CSS, proceed to learn the arguments of Javascript. You can take the Javascript course from Codecademy what's more.

You can also consult Pinch of the General Assembly to learn HTML, CSS and JavaScript interactively. Once you're done with Javascript, proceed to jQuery. Stick to Codecademy one more time. It is a short course. But, very useful for D3.

Finally, you need Scalable vector graphics (SVG). Plays a vital role in creating various shapes integrated into a d3 visualization. For this, You can follow this tutorial by w3schools.

At the moment, You should be able to create basic interactive web pages. Now is the time to get hands-on experience.

Test your skills: To test your knowledge of HTML, CSS, Javascript, Do This exercise of creating web projects. This should help you gain confidence in coding.

Additional: If you still feel deeply immersed in these arguments, Take this Complete course by Freecodecamp. If you successfully complete all levels of this course, You're more than ready to move on to the next step.

Paso 2: descargar, Install and run D3.js

Now you need to install a text editor where you can code. This is a crucial factor. Selecting a good text editor provides a real boost and excitement to the code. I use, I prefer and recommend Sublime Text. It is an open source publisher, Quick and easy to use. It supports many useful plugins and customization options to make the coding experience amazing.

After you've installed a text editor, The next step is to download and install the d3.js library, which is also quite simple.

You can download the full d3 zip file from here. Create a folder on your local machine and unzip it. You will find the named javascript files d3.js Y d3.min.js.

To load the d3 library into your text editor, You can do this in a variety of ways, either from your local machine or from your source. Don't forget to add this script in the :

<!--Load D3 from source website-->
<src= script"http://d3js.org/d3.v3.min.js"></script> 
<!--Load D3 from local machine-->
<script type="text/javascript" src="https://www.analyticsvidhya.com/learning-paths-data-science-business-analytics-business-intelligence-big-data/newbie-d3-js-expert-complete-path-create-interactive-visualization-d3-js/d3.min.js"></script>

Paso 3: Get started in D3 – First example

Then, You should work through Chapter 1B of the course from Udacity. Introduce you to the concepts of D3 through a simple example. Once you've worked with a basic example, You can see more details about how to create data-driven items.

You can look at either:

  • Chapter 7 – Chapter 20 of dashingd3 tutorials; O
  • Chapter 4 – Chapter 17 from the book of Scott Murray

Both cover various aspects of d3 in detail, Assuming you have prior knowledge of HTML, css, javascript.

Paso 4: Practice Time

At this stage, You should have gained practical knowledge of D3. You should now be comfortable coding using these different languages. Let's now practice some basic visualization techniques that you have learned in the previous steps.

The idea behind these examples is to make you practice. Don't check the code at first. Try it for yourself first. After, Check the answer if you get stuck.

Example 1: Create a pie chart

<!DOCTYPE html>
<html>
<head>
 <title>Path with Line</title>
 <script type="text/javascript" src="https://www.analyticsvidhya.com/learning-paths-data-science-business-analytics-business-intelligence-big-data/newbie-d3-js-expert-complete-path-create-interactive-visualization-d3-js/d3.min.js"></script>
</head>
<body>
<script>
       var data = [20, 50, 80];
       var r = 150;

       var canvas = d3.select("body").append("svg")
                    .attr("width", 1500)
                    .attr("height", 1500);
       var color = d3.scale.ordinal()
                   .range(["orange", "red", "green"]);
       var group = canvas.append("g")
                   .attr("Transform", "Translate(200, 200)");
       var arc = d3.svg.arc()
                .innerRadius(80)
                .outerRadius(r);
       var pie = d3.layout.pie()
                 .value ( function(d) { return d; });
       var arcs = group.selectAll(".arc")
                 .data(pie(data))
                 .enter()
                 .append("g") 
                 .attr("class", "arc");
       arcs.append("path")
       .attr("d", arc)
       .attr("fill", function(d) { return color(d.data)});
       arcs.append("text")
       .attr("Transform", function(d) { return "Translate(" + arc.centroid(d) + ")"; })
       .attr("text-anchor", "middle")
       .attr("font-size", "1.5em")
       .text(function(d) { return d.data; });
</script>
</body>
</html>

Production: Does it look like this:

tarta

Example 2: crear un gráfico de barras animado

<!DOCTYPE html>
<html>
<head>
      <script type="text/javascript" src="https://www.analyticsvidhya.com/learning-paths-data-science-business-analytics-business-intelligence-big-data/newbie-d3-js-expert-complete-path-create-interactive-visualization-d3-js/d3.min.js"></script>
</head>
<body>
 
      <div class="container">
           <h2>Animated Bar Chart</h2>
                 <div id="chart"></div>
      </div>
<script>
  
       var bardata = [];

       for (var i=0; i<50; i++){
            bardata.push(Math.round(Math.random()*30))
       }

       bardata.sort(function compareNumbers(a,b){
            return a-b;
       })
             var margin = { top: 30, right: 30, bottom: 40, left: 50}

             var height = 400 - margin.top - margin.bottom,
                 width = 600 - margin.right - margin.left,
                 barWidth = 50,
                 barOffset = 5;

             var tempColor;

             var tooltip = d3.select('body').append('div')
                          .style('position', 'absolute')
                          .style('padding', '0 10px')
                          .style('background', 'white')
                          .style('opacity', 0)

             var yScale = d3.scale.linear()
                         .domain([0, d3.max(bardata)])
                         .range([0, height])

             var xScale = d3.scale.ordinal()
                         .domain(d3.range(0,bardata.length))
                         .rangeBands([0,width], .3)

             var color = d3.scale.linear()
                         .domain([0, bardata.length*.63, bardata.length])
                         .range(['#ffb832','#c61c6f','#d33682'])


             var myChart = d3.select('#chart').append('svg')
                         .style('background', '#e7e0cb')
                         .attr('width', width + margin.left + margin.right)
                         .attr('height', height + margin.top + margin.bottom)
                         .append('g')
                         .attr('transform','translate(' + margin.left+','+ margin.top + ')')
                         .selectAll('rect')
                         .data(bardata)
                         .enter()
                         .append('rect')

                          .style('fill', function(d,i){
                                 return color(i);
                             })
                         .attr('width', xScale.rangeBand())
                         .attr('x', function(d,i){
                                return xScale(i);
                             })
                         .attr('height', 0)
                         .attr('and', height)

                         .on('mouseover', function(d){

                             tooltip.transition()
                               .style('opacity', 0.9)
                             tooltip.html(d)
                                     .style('left', (d3.event.pageX - 35)+'px')
                                     .style('top', (d3.event.pageY - 40)+'px')


                         tempColor = this.style.fill;
                         d3.select(this)
                           .style('opacity', .5)
                           .style('fill', 'yellow')
                         })
                        .on('mouseout', function(d){
                          d3.select(this)
                               .style('opacity', 1)
                               .style('fill', tempColor)
                         })

                         myChart.transition()
                                .attr('height', function(d){
                                       return yScale(d);
                         })
                                .attr('and', function(d){
                                       Return height - yScale(d);
                         })
                        .Delay(function(d,i){
                                Return *20;
                         })
                        .Duration(5000)
                        .Ease('elastic')

            var vGuideScale = d3.scale.linear()
                              .domain([0, d3.max(bardata)])
                              .range([height, 0])

            var vAxis = d3.svg.axis()
                        .scale(vGuideScale)
                        .orient('left')
                        .ticks(10)

            var vGuide = d3.select('svg').append('g')
                vAxis(vGuide)

                vGuide.attr('transform','translate('+margin.left+',' + margin.top + ')')
                vGuide.selectAll('path')
                      .style({fill: 'none', stroke: '#000'})
                vGuide.selectAll('line')
                      .style({stroke: '#000'})

            var hAxis = d3.svg.axis()
                      .scale(xScale)
                      .orient('bottom')
                      .tickValues(xScale.domain().filter(function(d,i){
                           return !(i % (bardata.length/5));
                       }))

            var hGuide = d3.select('svg').append('g')
                        hAxis(hGuide)
                hGuide.attr('transform', 'translate('+margin.left+',' + (height + margin.top)                            + ')')
                hGuide.selectAll('path')
                      .style({fill: 'none', stroke: '#000'})
                hGuide.selectAll('line')
                      .style({stroke: '#000'})
 
</script>
</body>
 
</html>

Production: It is bar graphic se parece a esto: Click Here

Example 3: Create a simple map outline

I've demonstrated this example using the Boston neighborhood map. The idea is to understand the arguments of map-making, without diving into fancy stuff.

<html>
   <head>
       <title>Basic D3 map</title>
       <src= script"http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
       <src= script"neighborhoods.js"></script> 
</head>
<body>
    <script>
          var width = 700,
          height = 580;

          var svg = d3.select( "body" )
                   .append( "svg" )
                   .attr( "width", width )
                   .attr( "height", height );

          var g = svg.append( "g" );

          var albersProjection = d3.geo.albers()
              .scale( 190000 )
              .Rotate( [71.057,0] )
              .center( [0, 42.313] )
              .Translate( [width/2,height/2] );

          var geoPath = d3.geo.path()
              .Projection( albersProjection );
            
          g.selectAll( "path" )
           .data( neighborhoods_json.features )
           .enter()
           .append( "path" )
           .attr( "fill", "#Ccc" )
           .attr( "d", geoPath );

  </script>
</body>
</html>

Production: This is the Boston neighborhood map outline:

Map of Boston on D3

These examples are just to whet your appetite. Real gameplay starts with animated geographical maps. Once you feel comfortable creating these elemental visualizations, Take it to the next level. For maps, D3 works best with Geojson and Topojson formats. Geojson is the default geographic data file. But, Topojson is considered to be faster and capable of loading large datasets in small size (Compressed Data).

Other Helpful Resources

Here are some more helpful resources that you may find helpful:

  1. Github repository of d3.js tutorials
  2. Complete the Udacity course in d3.js
  3. Best Youtube Tutorial on d3.js
  4. D3 official website
  5. D3 Tips & Tricks: Free eBook

Even so, if you find D3 difficult to learn, Feel free to share your issues in the comments section below.

If you like what you have just read and want to continue your analytical learning, subscribe to our emails, Follow us on twitter or like ours Facebook page.

Subscribe to our Newsletter

We will not send you SPAM mail. We hate it as much as you.