简体   繁体   中英

D3: How to do an update pattern on normalized stacked bar chart?

I got my normalized stacked bar chart working, but I'm trying to add an update function & I'm having trouble getting it to work. Basically, I'm trying to add another column to my CSV file to help sort the data and it's messing with the graph. Here's what I have so far:

var aUtils = (function () {
  function init(options) { 
  var defaults = {};
  options = $.extend(defaults, options);

var margin = {top: 20, right: 20, bottom: 30, left: 40};

var containerWidth = $('.graph__container').width(),
    containerHeight = $('.graph__container').height(),
    width = containerWidth,
    height = containerHeight;

var svg = d3.select(".graph__container")
            .append('svg');
svg.attr({
   'width' : width,
  'height' : height
});

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

var x = d3.scaleBand()
          .rangeRound([0, width])
          .padding(0.1)
          .align(0.1);

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

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

var stack = d3.stack()
              .offset(d3.stackOffsetExpand);

d3.csv("data.csv", type, function(error, data) {
  if (error) throw error;

  data.sort(function(a, b) { return b[data.columns[1]] / b.total - a[data.columns[1]] / a.total; });

  x.domain(data.map(function(d) { return d.etailer; }));
  z.domain(data.columns.slice(1));

  var layer = g.selectAll(".layer")
    .data(stack.keys(data.columns.slice(1))(data))
    .enter().append("g")
      .attr("class", "layer")
      .attr("fill", function(d) { return z(d.key); });

  layer.selectAll("rect")
    .data(function(d) { return d; })
    .enter().append("rect")
      .attr("x", function(d) { return x(d.data.etailer); })
      .attr("y", function(d) { return y(d[1]); })
      .attr("height", function(d) { return y(d[0]) - y(d[1]); })
      .attr("width", x.bandwidth());

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

  g.append("g")
      .attr("class", "axis axis--y")
      .call(d3.axisLeft(y).ticks(10, "%"));

  var legend = layer.append("g")
      .attr("class", "legend")
      .attr("transform", function(d) { var d = d[d.length - 1]; return "translate(" + (x(d.data.etailer) + x.bandwidth()) + "," + ((y(d[0]) + y(d[1])) / 2) + ")"; });

  legend.append("line")
      .attr("x1", -6)
      .attr("x2", 6)
      .attr("stroke", "#000");

  legend.append("text")
      .attr("x", 9)
      .attr("dy", "0.35em")
      .attr("fill", "#000")
      .style("font", "10px sans-serif")
      .text(function(d) { return d.key; });

});

function type(d, i, columns) {
  for (i = 1, t = 0; i < columns.length; ++i) t += d[columns[i]] = +d[columns[i]];
  d.total = t;
  return d;
}
}

return { 
  init : init 
}
})();

$(document).ready(function() { 
  aUtils.init(); 
});

My CSV file looks like this:

category etailer brandname1 brandname 2 brandname 3
air, amazon, 3, 4, 5
air, walmart, 1, 2, 3
air, target, 7, 8, 1
wind, target, 3, 4, 5
wind, walmart, 0, 9, 5
wind, amazon, 3, 5, 8

Right now I can get it working without the "category" column, but as soon as I add the category column so I can start working on the update pattern, the whole chart breaks. To clarify, I want "etailer" to be x axis, I want to display the different categories separately based on a click from a select list. I haven't been able to find any similar example online. Any direction would be much appreciated!

I needed two main changes to fix this issue. The first is changing the type function to this:

    function type(d, i, columns) {
      for (i = 2, t = 0; i < columns.length; ++i) t += d[columns[i]] =  +d[columns[i]];
      d.total = t;
      return d;
    }

As you can see, I changed i = 1, to i = 2. Before I made this change, the function was trying to read the second column as a number.

My next change was to filter the data, using this function:

       categoryData = data.filter( function(d) {
        return d.category === category;
       });

I can't totally explain what this does, it worked ¯_(ツ)_/¯

I changed this line:

       var serie = g.selectAll(".serie")
      .data(stack.keys(data.columns.slice(2))(data))

To this:

      var serie = g.selectAll(".serie")
      .data(stack.keys(data.columns.slice(2))(categoryData))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM