使用d3.js获取要显示的水平堆栈条示例 [英] Getting horizontal stack bar example to display using d3.js

查看:67
本文介绍了使用d3.js获取要显示的水平堆栈条示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Stack Exchange上查看了如何创建水平堆叠条形示例,并发现: http://tributary .io/inlet/4966973

I looked on the Stack Exchange for how to create a horizontal stacked bar example, and found: http://tributary.io/inlet/4966973

基于以下内容: http://bl.ocks.org/mbostock/3943967

为了更好地理解此代码的工作方式,我在计算机上运行了Bostock的示例(通过SimpleHTTPServer等).

To better understand how this code works I got Bostock's example running on my machine (via SimpleHTTPServer, etc.).

但是,我无法让Gelicia的Tributary示例运行.我复制了gelicia的Tributary示例,并添加了Bostock的html代码(引至脚本),并添加了Tributary示例结尾处的以下功能,但未创建svg主体和生成的bar rect.但是没有明显的错误消息可以解决问题.

However, I couldn't get gelicia's Tributary example to run. I copied gelicia's Tributary example, and added Bostock's html code (leading up to the script), and additionally the functions below where the Tributary example ends, but the svg body and resulting bar rects aren't created. But there's no obvious error message to fix something.

我尝试在Bostock的函数中切换xs和ys,因为我读到这是从垂直堆叠到水平堆叠的条形图的主要转换问题,但这无济于事,并且再也没有出现错误.

I tried switching the xs and ys in Bostock's function since I read that was the main conversion issue from going from vertical to horizontal stacked bars, but that didn't help and once again no error appeared.

有人可以向我解释如何运行水平栏堆栈示例,以及尝试使它在html文档中工作时我做错了什么?

Can someone explain to me how to get the horizontal bar stack example to run, and what I've been done wrong in trying to get it to work within an html document?

<!DOCTYPE html>
<meta charset="utf-8">
<style>

body {
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  margin: auto;
  position: relative;
  width: 960px;
}

text {
  font: 10px sans-serif;
}

.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

form {
  position: absolute;
  right: 10px;
  top: 10px;
}

</style>
<form>
  <label><input type="radio" name="mode" value="grouped"> Grouped</label>
  <label><input type="radio" name="mode" value="stacked" checked> Stacked</label>
</form>
<script type="text/javascript" src="d3.v3.js"></script>
<script>
        //modified from Mike Bostock at http://bl.ocks.org/3943967 */

        var data = [
        {"key":"FL", "pop1":3000, "pop2":4000, "pop3":5000},
        {"key":"CA", "pop1":3000, "pop2":3000, "pop3":3000},
        {"key":"NY", "pop1":12000, "pop2":5000, "pop3":13000},
        {"key":"NC", "pop1":8000, "pop2":21000, "pop3":11000},
        {"key":"SC", "pop1":30000, "pop2":12000, "pop3":8000},
        {"key":"AZ", "pop1":26614, "pop2":6944, "pop3":30778},
        {"key":"TX", "pop1":8000, "pop2":12088, "pop3":20000}
        ];

        var n = 3, // number of layers
            m = data.length, // number of samples per layer
            stack = d3.layout.stack(),
            labels = data.map(function(d) {return d.key;}),

            //go through each layer (pop1, pop2 etc, that's the range(n) part)
            //then go through each object in data and pull out that objects's population data
            //and put it into an array where x is the index and y is the number
            layers = stack(d3.range(n).map(function(d) { 
                        var a = [];
                        for (var i = 0; i < m; ++i) {
                            a[i] = {x: i, y: data[i]['pop' + (d+1)]};  
                        }
                        return a;
                     })),

            //the largest single layer
            yGroupMax = d3.max(layers, function(layer) { return d3.max(layer, function(d) { return d.y; }); }),
            //the largest stack
            yStackMax = d3.max(layers, function(layer) { return d3.max(layer, function(d) { return d.y0 + d.y; }); });

        var margin = {top: 40, right: 10, bottom: 20, left: 50},
            width = 677 - margin.left - margin.right,
            height = 533 - margin.top - margin.bottom;

        var y = d3.scale.ordinal()
            .domain(d3.range(m))
            .rangeRoundBands([2, height], .08);

        var x = d3.scale.linear()
            .domain([0, yStackMax])
            .range([0, width]);

        var color = d3.scale.linear()
            .domain([0, n - 1])
            .range(["#aad", "#556"]);

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

        var layer = svg.selectAll(".layer")
            .data(layers)
          .enter().append("g")
            .attr("class", "layer")
            .style("fill", function(d, i) { return color(i); });

        layer.selectAll("rect")
            .data(function(d) { return d; })
            .enter().append("rect")
            .attr("y", function(d) { return y(d.x); })
            .attr("x", function(d) { return x(d.y0); })
            .attr("height", y.rangeBand())
            .attr("width", function(d) { return x(d.y); });

        var yAxis = d3.svg.axis()
            .scale(y)
            .tickSize(1)
            .tickPadding(6)
            .tickValues(labels)
            .orient("left");

        svg.append("g")
            .attr("class", "y axis")
            .call(yAxis);



        //ADD IN BOSTOCK CODE -- replace xs with ys and vice versa

        d3.selectAll("input").on("change", change);

        var timeout = setTimeout(function() {
          d3.select("input[value=\"grouped\"]").property("checked", true).each(change);
        }, 2000);

        function change() {
          clearTimeout(timeout);
          if (this.value === "grouped") transitionGrouped();
          else transitionStacked();
        }

        function transitionGrouped() {
          x.domain([0, xGroupMax]);

          rect.transition()
              .duration(500)
              .delay(function(d, i) { return i * 10; })
              .attr("y", function(d, i, j) { return y(d.y) + y.rangeBand() / n * j; })
              .attr("width", y.rangeBand() / n)
            .transition()
              .attr("x", function(d) { return x(d.x); })
              .attr("height", function(d) { return height - x(d.x); });
        }

        function transitionStacked() {
          x.domain([0, xStackMax]);

          rect.transition()
              .duration(500)
              .delay(function(d, i) { return i * 10; })
              .attr("x", function(d) { return x(d.x0 + d.x); })
              .attr("height", function(d) { return x(d.x0) - x(d.x0 + d.x); })
            .transition()
              .attr("y", function(d) { return y(d.y); })
              .attr("width", y.rangeBand());
        }

        // Inspired by Lee Byron's test data generator.
        function bumpLayer(n, o) {

          function bump(a) {
            var y = 1 / (.1 + Math.random()),
                x = 2 * Math.random() - .5,
                z = 10 / (.1 + Math.random());
            for (var i = 0; i < n; i++) {
              var w = (i / n - x) * z;
              a[i] += y * Math.exp(-w * w);
            }
          }

          var a = [], i;
          for (i = 0; i < n; ++i) a[i] = o + o * Math.random();
          for (i = 0; i < 5; ++i) bump(a);
          return a.map(function(d, i) { return {y: i, x: Math.max(0, d)}; });

          }

        </script>   
    </body>
</html>

推荐答案

页面上似乎没有svg元素.您只需添加您的身体(表格上方或下方),它便会起作用.

It looks like you don't have an svg element on your page. You can simply add in your body (above or below your form) and it should work.

(默认情况下,tributary为您创建了一个svg元素,因为它们在此处运行,而不是在您的示例中运行)

(tributary creates an svg element for you by default, which is they the code runs there and not in your example)

这篇关于使用d3.js获取要显示的水平堆栈条示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆