1
votes

I am trying to make a grouped bar chart with negative and positive values. The problem is that I can only draw the positive values. The Y-axis stops at 0 instead of at the lowest value. How can I make sure the bar chart can have positive and negative values at the same time?

This is my CSV:

name,value,koken,kcal
Ab,-15,0,-7
C,22,1,2
Bc,-20,0,-10
E,2,1,20

And this is my code:

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

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

var x0 = d3.scaleBand()
    .rangeRound([0, width]);

var x1 = d3.scaleBand()
    .padding(0.05);

var y = d3.scaleLinear()
    .rangeRound([height, 0]);

var z = d3.scaleOrdinal()
    .range(["#98abc5", "#8a89a6", "#7b6888"]);

d3.csv("flare0.csv", function(d, i, columns) {
    for (var i = 1, n = columns.length; i < n; ++i) d[columns[i]] = +d[columns[i]];
    return d;
},
    function(error, data) {
    if (error) throw error;

    var keys = data.columns.slice(1);

    x0.domain(data.map(function(d) { 
        return d.name; }));

        x1.domain(keys).rangeRound([0, x0.bandwidth()]);

    y.domain([0, d3.max(data, function(d) { return d3.max(keys, function(key) { return d[key]; }); })]).nice();

  console.log(data);
    g.append("g")
        .selectAll("g")
        .data(data)
        .enter().append("g")
        .attr("class", function(d) { return d < 0 ? "bar negative" : "bar positive"; })
            .attr("transform", function(d) { return "translate(" + x0(d.name) + ",0)"; })
        .selectAll("rect")
        .data(function(d) { return keys.map(function(key) { return {key: key, value: d[key]}; }); })
        .enter().append("rect")
        .attr("x", function(d) { return x1(d.key); })
        .attr("y", function(d) { return y(d.value); })
        .attr("width", x1.bandwidth())

        .attr("height", function(d) {
            console.log(height - y(d.value));
            return height - y(d.value); })
        .attr("fill", function(d) { return z(d.key); });

    g.append("g")
        .attr("class", "axis")
        .attr("transform", "translate(0," + height + ")")
        .call(d3.axisBottom(x0));

    g.append("g")
        .attr("class", "axis")
        .call(d3.axisLeft(y).ticks(null, "0"))
        .append("text")
        .attr("x", 20)
        .attr("y", y(y.ticks().pop()) + 0.5)
        .attr("dy", "0.32em")
        .attr("fill", "#000")
        .attr("font-weight", "bold")
        .attr("text-anchor", "start")
        .text("Population");       
});
2

2 Answers

0
votes

This gist provides an example that may get you closer. By adding the following code, I've managed to get both negative annd positive values to appear together:

 y.domain([
    d3.min(data, function(d) { return d3.min(keys, function(key) { return d[key]; }); }),
    d3.max(data, function(d) { return d3.max(keys, function(key) { return d[key]; }); })]).nice();

Here's a updated Plunker: http://plnkr.co/edit/pZzFKaiQWNVJm0SuK9kW?p=preview

If you use the gist I provided as a reference, you'll be able to modify your code so that the bars are drawn from 0, rather than the lowest value.

0
votes

First, change your y scale domain to get the negative values:

y.domain([d3.min(data, function(d) {
    return d3.min(keys, function(key) {
        return d[key];
    });
}), d3.max(data, function(d) {
    return d3.max(keys, function(key) {
        return d[key];
    });
})]).nice();

If you want a shorter code, consider using d3.extent here.

Then, change your math: it makes no sense the bars coming from the base of the axis and going up. Instead of that, all bars should come from the 0 value in the y axis, and go up if they are positive, otherwise go down if they are negative:

.attr("y", function(d) {
    return d.value > 0 ? y(d.value) : y(0);
})
.attr("height", function(d) {
    return d.value > 0 ? y(0) - y(d.value) : y(d.value) - y(0);
})

Here is your code with those changes:

var csv = `name,value,koken,kcal
Ab,-15,0,-7
C,22,1,2
Bc,-20,0,-10
E,2,1,20`;

var margin = {
    top: 20,
    right: 30,
    bottom: 40,
    left: 30
  },
  width = 600 - margin.left - margin.right,
  height = 400 - margin.top - margin.bottom;

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

var x0 = d3.scaleBand()
  .rangeRound([0, width]);

var x1 = d3.scaleBand()
  .padding(0.05);

var y = d3.scaleLinear()
  .rangeRound([height, 0]);

var z = d3.scaleOrdinal()
  .range(["#98abc5", "#8a89a6", "#7b6888"]);

var data = d3.csvParse(csv, function(d, i, columns) {
  for (var i = 1, n = columns.length; i < n; ++i) d[columns[i]] = +d[columns[i]];
  return d;
});

var keys = data.columns.slice(1);

x0.domain(data.map(function(d) {
  return d.name;
}));

x1.domain(keys).rangeRound([0, x0.bandwidth()]);

y.domain([d3.min(data, function(d) {
  return d3.min(keys, function(key) {
    return d[key];
  });
}) * 1.1, d3.max(data, function(d) {
  return d3.max(keys, function(key) {
    return d[key];
  });
}) * 1.1]).nice();

g.append("g")
  .selectAll("g")
  .data(data)
  .enter().append("g")
  .attr("class", function(d) {
    return d < 0 ? "bar negative" : "bar positive";
  })
  .attr("transform", function(d) {
    return "translate(" + x0(d.name) + ",0)";
  })
  .selectAll("rect")
  .data(function(d) {
    return keys.map(function(key) {
      return {
        key: key,
        value: d[key]
      };
    });
  })
  .enter().append("rect")
  .attr("x", function(d) {
    return x1(d.key);
  })
  .attr("y", function(d) {
    return d.value > 0 ? y(d.value) : y(0);
  })
  .attr("width", x1.bandwidth())

.attr("height", function(d) {
    return d.value > 0 ? y(0) - y(d.value) : y(d.value) - y(0);
  })
  .attr("fill", function(d) {
    return z(d.key);
  });

g.append("g")
  .attr("class", "axis")
  .attr("transform", "translate(0," + height + ")")
  .call(d3.axisBottom(x0));

g.append("g")
  .attr("class", "axis")
  .call(d3.axisLeft(y).ticks(null, "0"))
  .append("text")
  .attr("x", 20)
  .attr("y", y(y.ticks().pop()) + 0.5)
  .attr("dy", "0.32em")
  .attr("fill", "#000")
  .attr("font-weight", "bold")
  .attr("text-anchor", "start")
  .text("Population");
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="600" height="400"></svg>