Designing Responsive Charts Using D3JS

This article is all about how easy it is to make your charts responsive by making a few changes in your code. So this article is all about how to make your chart more user friendly using a few cool effects.

Outlines

  • Overview
  • Responsiveness
    • Zoom Effect
    • Scroll Effect
  • Demo
    • HTML Snippet
    • JavaScript Snippet
    • CSS Snippet
    • Output
      • Zoom Effect
      • Scroll Effect
  • Summary

Overview

I hope you guys already have some feel of D3.JS and it's respective functionality based on my previous article. This article is one more step in that series. So by reading the core of this article you will have some ideas in your mind about this article.

So this article explains how easily and effectively you can make your charts responsive and interactive using certain lines of codes (in JavaScript). Let's see what you will learn in this article.

Responsiveness | Explanation

I guess all of you must be familiar with "responsive or responsivness" that simply means how to make our things more and more user friendly.

For making my charts a bit responsive I am using these 2 effects:

Responsiveness

Zoom Effect

In the Zoom effect if you click the output then the chart will be magnified. You can do that function up to a limit and power of being Zoomed repetitively directly proportional to the number of dependent clicks.

Defining Attributes:

  1. // Calling Chart Attributes and Behaviour  
  2. var chart = d3.select(location).append("svg")  
  3.     .attr("class""chart")  
  4.     .attr("width", graph_width + 20)  
  5.     .attr("height", graph_height + 20).  
  6.     call(d3.behavior.zoom().x(x).scaleExtent([1, 8]).on("zoom", zoom)); 

Here is a Zoom function that will create a Zoom effect for us.

  1. function zoom() {  
  2.     chart.select(".xaxis").call(xAxis);  
  3.     chart.select(".yaxis").call(yAxis);  
  4.     chart.selectAll(".chart rect").attr("transform""translate(" + d3.event.translate[0] + ",0)scale(" + d3.event.scale + ", 1)"); 

You will see the functioning of that effect later in this article in the Output portion. Until then check out the scroll effect.

Scroll Effect

From scroll effect I mean, you can scroll your chart along any axis by simply holding the background through your mouse cursor. In this article's code snippet there is only a X axis (left and right hand scrolling) effect.

But you can make it along the y axis too.

Demo

HTML Snippet

Just write a simple HTML snippet and embed JavaScript and CSS code snippets in it. Don't forget to provide this tag line:

  1. <div id="post"></div> 

JavaScript Snippet

Here is the JavaScript snippet that will generate a Column chart, or I better say a Responsive (Zooming Effect chart) Chart with it. For that I am using a simple JavaScript structure like code snippet and D3.JS functionality in it along with JSON data.

  1. // JSON Data  
  2.    
  3.  var data = [  
  4.      { "date""2012-01-01""num": 5 },  
  5.      { "date""2012-01-05""num": 10 },  
  6.      { "date""2012-01-10""num": 22 },      
  7.      { "date""2012-01-15""num": 72 },  
  8.      { "date""2012-01-20""num": 87 },  
  9.      { "date""2012-01-21""num": 90 }  
  10.  ];  
  11.    
  12.  // Function for Creating the require Chart  
  13.  function draw() {  
  14.    
  15.      // Providing Require Parameters  
  16.      var location = "#post"  
  17.      var month_names = ['Jan''Feb''Mar''Apr''May''Jun''Jul''Aug''Sep''Oct''Nov''Dec'];  
  18.      var graph_width = 500;  
  19.      var graph_height = 200;  
  20.    
  21.      // Declaring Some functionality Oriented Parameters  
  22.      var values = _.pluck(data, 'num');  
  23.      var max_val = d3.max(values);  
  24.      var v_scale = graph_height / max_val;  
  25.      var data_counts = data.length;  
  26.      var bar_width = graph_width / data_counts;  
  27.      var minDate = new Date(data[0]["date"]);  
  28.      var maxDate = new Date(data[data.length - 1]["date"]);  
  29.    
  30.      // Defining Range of a Graph  
  31.      var y = d3.scale.linear()  
  32.          .domain([0, max_val])  
  33.          .range([graph_height, 0]);  
  34.    
  35.      console.log(minDate);  
  36.      var x = d3.time.scale().domain([minDate, maxDate]).range([0, graph_width]);  
  37.    
  38.      // Calling Chart Attributes and Behaviour  
  39.      var chart = d3.select(location).append("svg")  
  40.          .attr("class""chart")  
  41.          .attr("width", graph_width + 20)  
  42.          .attr("height", graph_height + 20).  
  43.          call(d3.behavior.zoom().x(x).scaleExtent([1, 8]).on("zoom", zoom));  
  44.    
  45.      var lines = chart.selectAll("line");  
  46.    
  47.      // Functionality for Y Axis  
  48.      var lines_y = lines  
  49.          .data(x.ticks(5))  
  50.      .enter().append("line")  
  51.      .attr("x1", x)  
  52.      .attr("x2", x)  
  53.      .attr("y1"function (d) {  
  54.          return graph_height - 20 - d;  
  55.      })  
  56.      .attr("y2", graph_height)  
  57.      .style("stroke""#ccc");  
  58.    
  59.      // Functionality for X Axis  
  60.      var lines_x = lines  
  61.          .data(y.ticks(10))  
  62.          .enter().append("line")  
  63.          .attr("x1", 0)  
  64.          .attr("x2", graph_width)  
  65.          .attr("y1", y)  
  66.          .attr("y2", y)  
  67.          .style("stroke""#ccc");  
  68.    
  69.      // Scalling of Chart for both Axis  
  70.      xAxis = d3.svg.axis().scale(x);  
  71.      yAxis = d3.svg.axis().scale(y).orient("left");  
  72.    
  73.      chart.append("svg:g")  
  74.          .attr("class""xaxis")  
  75.          .attr("transform""translate(0,200)")  
  76.          .call(xAxis);  
  77.    
  78.      chart.append("svg:g")  
  79.          .attr("class""yaxis")  
  80.          .attr("transform""translate(25,0)")  
  81.          .call(yAxis);  
  82.    
  83.      var rect = chart.selectAll("rect")  
  84.          .data(data).enter()  
  85.          .append("rect")  
  86.          .attr("x"function (d, i) { return x(new Date(d["date"])) + 20; })  
  87.          .attr("y"function (d, i) { return graph_height - (d["num"] * v_scale); })  
  88.          .attr("width", x(new Date(data[1]["date"])))  
  89.          .attr("height"function (d, i) { return d["num"] * v_scale; });  
  90.    
  91.      // Calling ZOOM function for some Responsive Effects  
  92.      function zoom() {  
  93.          chart.select(".xaxis").call(xAxis);  
  94.          chart.select(".yaxis").call(yAxis);  
  95.          chart.selectAll(".chart rect").attr("transform""translate(" + d3.event.translate[0] + ",0)scale(" + d3.event.scale + ", 1)");  
  96.      }  
  97.  }  
  98.    
  99.  draw(); 

CSS Snippet

Here's our simple CSS snippet:

  1. div#post  
  2. {  
  3.     width:500;  
  4.     height:210;  
  5. }  
  6. .chart rect  
  7. {  
  8.     stroke: white;  
  9.     fill: steelblue;  

Output

This is the real output you will get through that code snippet.

Scroll Effect

Output | Zoom Effect

+2 Zoom Effect

First of all I will you why I am calling it responsive. First of all I'll show you the Zoom effect.

If you double-click on the preceding output then you will get a normal Zoom effect, that is shown in the following image:

Normal Zoom Effect

+3 Zoom Effect

For the sake of being responsive, if you click thrice then you will get something like that in your browser (More Zoom effect, extra wide bars).

More Zoom Effect

+5 Zoom Effect

Now, if you want an increasingly magnified chart then continue to click (maybe 5 to 7 times) and then you will get something like that:

Extra Zoom Effect

For more and more effects try clicking.

Output | Scrolling Effect

Now I will show you scrolling responsiveness of this graph. You can do this on the right and left hand side scrolling.

Right Side Scrolling Effect

For that effect if you hold the background and swap the cursor to the right then you will get your chart something like the following (Right Scrolling Effect):

Right Side Scroll Effect

Left Side Scrolling Effect

For that effect if you hold the background and swap the cursor to the left then you will get your chart something like the following:

Left Side Scroll Effect

Summary

I hope you have enjoyed this article and learned something. That was my original intent. Keep in touch for more informative and interesting technology terms.

Meanwhile if you have any query, then feel free to ask.

#HappyCoding!

Up Next
    Ebook Download
    View all
    Learn
    View all