在 D3 中将堆叠条形图的方向从垂直更改为水平

Changing the orientation of the Stacked bar Chart from Vertical to Horizontal in D3

我正在将响应式堆叠条形图的方向从垂直更改为水平,但它在更改内容后没有显示任何内容,遵循来自 stackover 流程​​的其他一些示例,例如 here and here。 这涉及堆叠条形图 这是 fiddle

中垂直堆叠条形图的代码

但是当前的工作代码是here

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

      var width = 600 - margin.left - margin.right,
        height = 600 - margin.top - margin.bottom;

      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 + ")");


      /* Data in strings like it would be if imported from a csv */

      var data = [{
          year: "A",
          redDelicious: "10",
          mcintosh: "5",
          oranges: "19"
        }, {
          year: "B",
          redDelicious: "12",
          mcintosh: "0",
          oranges: "15"
        }, {
          year: "C",
          redDelicious: "05",
          mcintosh: "0",
          oranges: "28"
        }, {
          year: "D",
          redDelicious: "14",
          mcintosh: "0",
          oranges: "12"
        },

      ];
      $("#btn").on("click", function(){
        d3.selectAll("svg > g > g").remove();
        data[1].mcintosh = (Number(data[1].mcintosh) + 1).toString();
        console.log(1,data);
        update();
      });
      update();
function update(){
      var orangeData = data.map(function(d) {
        return {
          year: d.year,
          oranges: +d.oranges
        }
      });
      console.log(orangeData)



      // Transpose the data into layers
      var dataset = d3.layout.stack()(["redDelicious", "mcintosh"].map(function(skillset) {
        return data.map(function(d) {
          return {
            y: d.year,
            x: +d[skillset]
          };
        });
      }));
      console.log(dataset)

   xMax = d3.max(dataset, function(group) {
            return d3.max(group, function(d) {
                return d.x + d.x0;
            });
        }),
        xScale = d3.scale.linear()
            .domain([0, xMax])
            .range([0, width]);
        months = dataset[0].map(function(d) { return d.y; });    

         yScale = d3.scale.ordinal()
            .domain(months)
            .rangeRoundBands([0, height], .1);

      // Set x, y and colors
    /*  var y = d3.scale.ordinal()
         .domain([0, d3.max(dataset, function(d) {
          return d3.max(d, function(d) {
          return d.y;
          });
        })])
        .rangeRoundBands([height, 0], 0.02);

      var x = d3.scale.linear()
          .domain(dataset[0].map(function(d) {

          return d.x0 + d.x;
        }))
        .range([10, width-10]); */

      var colors = ["#b33040", "#d9d574"];
       var backcolors = ["red", "blue","green","pink"];


      // Define and draw axes
      var yAxis = d3.svg.axis()
        .scale(yScale)
        .orient("left");

      var xAxis = d3.svg.axis()
        .scale(xScale)
        .orient("bottom").ticks(5)
        .tickSize(-width, 0, 0);
     /*   .tickFormat(function(d) {
          return 0
        });*/
      //  .tickFormat(d3.time.format("%Y"));

     svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

      svg.append("g")
        .attr("class", "y axis")
        .call(yAxis).attr("transform", "rotate(-0)")
        .attr("y", 6)
        .attr("dy", ".71em")
        .style("text-anchor", "end");


        // Creating the Average Bar for the Semester
        svg.selectAll(".bar1").data(orangeData).enter().append("g")
        .attr("class", "bar1").append("rect")
        .attr("y", function(d) {
          return y(d.year) ; // center it
        })
        .attr("width", x.rangeBand()) // make it slimmer
        .attr("x", function(d) {
          return x(d.oranges);
        })
        .attr("width", function(d) {
          return width - x(d.oranges);
        });



      // Create groups for each series, rects for each segment in Stacked Bar 
      var groups = svg.selectAll("g.cost")
        .data(dataset)
        .enter().append("g")
        .attr("class", "cost")
        .style("fill", function(d, i) {
          return colors[i];
        });

      var rect = groups.selectAll("rect")
        .data(function(d) {
          return d;
        })
        .enter()
        .append("rect")
        .attr("y", function(d,y) {
          return yScale(d.y)  + 20 ;
        })
        .attr("x", function(d) {
          return xScale(d.x0 );
        })
        .attr("width", function(d) {
          return xScale(d.x);
        })
        .attr("height", yScale.rangeBand() -40 );
        }

来自 this answer :

您可以像这样旋转整个图表:

.attr("transform","rotate(90 200 200)");

查看更新后的 fiddle:https://fiddle.jshell.net/wtp1qmb2/

代码中需要改进的几点:不要混用 Jquery 和 D3

$("#btn").on("click", function(){
    d3.selectAll("svg > g > g").remove();
    data[1].mcintosh = (Number(data[1].mcintosh) + 1).toString();
    console.log(1,data);
    update();
  });

可以改成

d3.select("#btn").on("click", function(){
    // CODE
}