Search code examples
javascriptd3.jsbar-charthierarchyhierarchical

How can I create hierarchical bar chart in d3.js


I wanted to use the Sortable Bar Chart of Mike Bostock without it's transition property and sort the bars according to their lenght but I couldn't. I want the bars just like this. without interactivity.

<!DOCTYPE html>
<meta charset="utf-8">
<body>
<style>

body {
  font: 10px sans-serif;
}

.bar rect {
  fill: steelblue;
}

.bar text {
  fill: white;
}

.axis path, .axis line {
  fill: none;
  stroke: black;
  shape-rendering: crispEdges;
}

</style>
<script src="http://mbostock.github.com/d3/d3.js"></script>
<script>

var margin = {top: 0, right: 10, bottom: 20, left: 10},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var index = d3.range(24),
    data = index.map(d3.random.normal(100, 10));

var x = d3.scale.linear()
    .domain([0, d3.max(data)])
    .range([0, width]);

var y = d3.scale.ordinal()
    .domain(index)
    .rangeRoundBands([0, height], .1);

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var bar = svg.selectAll(".bar")
    .data(data)
    .enter().append("g")
    .attr("class", "bar")
    .attr("transform", function(d, i) { return "translate(0," + y(i) + ")";      });

bar.append("rect")
    .attr("height", y.rangeBand())
    .attr("width", x);

bar.append("text")
    .attr("text-anchor", "end")
    .attr("x", function(d) { return x(d) - 6; })
    .attr("y", y.rangeBand() / 2)
    .attr("dy", ".35em")
    .text(function(d, i) { return i; });

svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.svg.axis()
    .scale(x)
    .orient("bottom"));

//var sort = false;

    //setInterval(function() {

    //  if (sort = !sort) {
    //  index.sort(function(a, b) { return data[a] - data[b]; });
    //  } else {
    //  index = d3.range(24);
    //  }

    //  y.domain(index);

    //  bar.transition()
    //    .duration(750)
    //    .delay(function(d, i) { return i * 50; })
    //    .attr("transform", function(d, i) { return "translate(0," + y(i) + ")"; });

    //}, 5000);

var hierarchy = d3.layout.partition()
    .data(function(d) { return d.data; });

</script>

I removed the the code from var sort = false; part and added var hierarchy =.. part but It's still not working. How can I make it?

Any help will be appreciated. Thanks.


Solution

  • You should add the following line to sort the values:

    index.sort(function(a, b) { return data[b] - data[a]; });
    

    Check out the jsfiddle: http://jsfiddle.net/k9rcyeyo/