Introduction to D3.js {Part – 2}

Table of contents
Reading Time: 2 minutes

In our previous blog post we saw how to create a simple histogram based on data. But still our chart is not ideal chart as the range of data in array can vary from too small to very large numbers that might not fit in our SVG canvas created by D3 for e.g. in our last blog post if one element in the array is 120 then the width of bar corresponding to that number would be 120 * 10 = 1200px which is more than the width, 600px, of the canvas of D3 ; in this case any bar which exceeds the width 600px will stop at the right edge of the canvas and this representation of data would be incorrect. To cope up with these glitches D3 provides support of scaling our bars (or curves or colors or any SVG shape) to adjust in the canvas of the D3 so that from smallest element in dataset to largest element in dataset can fit in correctly and relatively (to each other).

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters

<!DOCTYPE html>
<script type="text/javascript" src=""></script&gt;
var dataArray = [120, 40, 50, 160];
var width = 500;
var height = 500;
var widthScale = d3.scaleLinear()
.domain([0, 160]) //(Minimum, Maximum)
.range([0, width]);
var canvas ="body")
.attr("width", width)
.attr("height", height);
var bars = canvas.selectAll("rect")
.attr("width", function(d){ return widthScale(d) })
.attr("height", 60)
.attr("y", function(d,i){return i*62});

In the code above we created a linear scale with scaleLinear() method of the d3 object. The values inside the domain() method must be the minimum and maximum values in the dataset – here I hard-coded the minimum and maximum values but D3 also has various methods to do calculations on the dataset to calculate the minimum, maximum, mean, median etc. The range() method sets the boundaries of the bars of our histogram. Here the whole canvas width is taken as the size of biggest bar in the histogram.


Thanks for reading, like and share.

Written by 

Principal Architect at Knoldus Inc