Search code examples
d3.js

D3 v4 bar chart X axis with negative values


I was using this example https://gist.github.com/mbostock/2368837 to plot a bar chart with negative and positive values but i am not able to set the negative x axis correctly. Can someone please tell me what my error is?

var margin = {top: 30, right: 10, bottom: 50, left: 50},
    width = $('.col-lg-12').width(),
    height = 420;

// Add svg to
var svg = d3.select('#id').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 + ')');

// set the ranges
var y = d3.scaleBand()
    .range([height, 0])
    .padding(0.1);

var x = d3.scaleLinear()
    .range([0, width]);

// Scale the range of the data in the domains
x.domain([0, d3.max(data, function (d) {
    return Math.abs(d.value);
})]);
y.domain(data.map(function (d) {
    return d.dataset;
}));

// append the rectangles for the bar chart
svg.selectAll(".bar")
    .data(data)
    .enter().append("rect")
    .attr("class", function (d) {
        return "bar bar--" + (d.value < 0 ? "negative" : "positive");
    })
    .attr("x", function (d) {
        return x(Math.min(0, d.value));
    })
    .attr("y", function (d) {
        return y(d.dataset);
    })
    .attr("width", function (d) {
        return Math.abs(x(d.value) - x(0));
    })
    .attr("height", y.bandwidth());

// add the x Axis
svg.append("g")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x));

// add the y Axis
svg.append("g")
    .attr("class", "y axis")
    .attr("transform", "translate(" + x(0) + ",0)")
    .call(d3.axisRight(y));

Screenshot of the problem


Solution

  • The problem is just the x domain. Since you have negative values, instead of:

    x.domain([0, d3.max(data, function (d) {
        return Math.abs(d.value);
    })]);
    

    It should be:

    x.domain(d3.extent(data, function (d) {
        return d.value;
    }));
    

    Here is a demo using your code with fake data:

    var margin = {top: 30, right: 10, bottom: 50, left: 50},
        width = 500,
        height = 300;
    		
    var data = [{value: 10, dataset:"barbaz"},
    {value: 40, dataset:"barbar"},
    {value: -10, dataset:"foobaz"},
    {value: 50, dataset:"foobar"},
    {value: 30, dataset:"baz"},
    {value: -20, dataset:"bar"},
    {value: 70, dataset:"foo"}];
    
    // Add svg to
    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 + ')');
    
    // set the ranges
    var y = d3.scaleBand()
        .range([height, 0])
        .padding(0.1);
    
    var x = d3.scaleLinear()
        .range([0, width]);
    
    // Scale the range of the data in the domains
    x.domain(d3.extent(data, function (d) {
        return d.value;
    }));
    y.domain(data.map(function (d) {
        return d.dataset;
    }));
    
    // append the rectangles for the bar chart
    svg.selectAll(".bar")
        .data(data)
        .enter().append("rect")
        .attr("class", function (d) {
            return "bar bar--" + (d.value < 0 ? "negative" : "positive");
        })
        .attr("x", function (d) {
            return x(Math.min(0, d.value));
        })
        .attr("y", function (d) {
            return y(d.dataset);
        })
        .attr("width", function (d) {
            return Math.abs(x(d.value) - x(0));
        })
        .attr("height", y.bandwidth());
    
    // add the x Axis
    svg.append("g")
        .attr("transform", "translate(0," + height + ")")
        .call(d3.axisBottom(x));
    
    // add the y Axis
    svg.append("g")
        .attr("class", "y axis")
        .attr("transform", "translate(" + x(0) + ",0)")
        .call(d3.axisRight(y));
    .bar--positive {
      fill: steelblue;
    }
    
    .bar--negative {
      fill: darkorange;
    }
    <script src="https://d3js.org/d3.v4.min.js"></script>