While searching for JavaScript graphical libraries to create module dependency graphs, I found D3.js. Today, I created a simple sorting algorithm visualization using it.

Code demystify

var w = 300, h = 100, svg;

svg = d3.select("#graph")
        .attr("width", w)
        .attr("height", h);

This creates a svg using d3.js with width = 300 and height = 100.

var rects = svg.selectAll("rect")
               .data([10, 20])

To display bars in svg will need rect rectangles. D3.js provides enter, where you can create new nodes for incoming data ([10, 20]).

At this step, these rects are not assigned with information of its width, height and position yet.

rects.attr("x", function(d, i) { return i * 21; })
     .attr("y", h)
     .attr("width", 20)
     .attr("height", function(d, i) { return d; })

Above lines will assign <x, y> position and <width, height> to each rect. d is the data associated with the rects (10 for rects[0], 20 for rects[1]) and i is the index of rect in rects.

To update the rects, you will do the similar using new data and transition:

function redraw(newData) {
    var rects = svg.selectAll("rect")
                   .duration(1000) // 1s

    // bind the x, y, width, height again
    // ...

These are all the basic code required to display the bar chart. You will then call redraw() in algorithms at each step.

D3.js Tutorials