D3js – change Vertical bar chart to Horizontal bar chart

I just did the same thing last night, and I basically ended up rewriting the code as it was quicker than fixing all the bugs but here’s the tips I can give you.

The biggest issues with flipping the x and y axis will be with things like return h - yScale(d.global) because height is calculated from the “top” of the page not the bottom.

Another key thing to remember is that when you set .attr("x", ..) make sure you set it to 0 (plus any padding for the left side) so = .attr("x", 0)"

I used this tutorial to help me think about my own code in terms of horizontal bars instead – it really helped

http://hdnrnzk.me/2012/07/04/creating-a-bar-graph-using-d3js/

here’s my own code making it horizontal if it helps:

var w = 600;
var h = 600;
var padding = 30;

var xScale = d3.scale.linear()
        .domain([0, d3.max(dataset, function(d){
                                return d.values[0]; })]) //note I'm using an array here to grab the value hence the [0]
        .range([padding, w - (padding*2)]);

        var yScale = d3.scale.ordinal()
            .domain(d3.range(dataset.length))
            .rangeRoundBands([padding, h- padding], 0.05);

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

        svg.selectAll("rect")
            .data(dataset)
            .enter()
            .append("rect")
            .attr("x", 0 + padding)
            .attr("y", function(d, i){
            return yScale(i);
            })
            .attr("width", function(d) {
                return xScale(d.values[0]);
            })
            .attr("height", yScale.rangeBand())

Leave a Comment