在D3js中创建条形图

时间:2014-05-29 19:48:11

标签: javascript d3.js

我正在关注本书交互式数据可视化网站的示例,其中涉及使用rect创建栏。我面临的问题是每个酒吧的起源,它正在向下滑动。代码如下:

<!DOCTYPE html>
<meta charset="utf-8">
<html>
  <head>
    <title>Census</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="../d3/d3.min.js"></script>
  </head>
  <body>
  <style>
      div.bar {
        display: inline-block;
        width: 20px;
        height: 75px; /* We'll override height later */
        background-color: teal;
        margin-right: 5px;
        margin-bottom: 320px;
        }
        rect{
            margin-right: 5px;
}
  </style>
      <script>
          //var dataset = [ 5,10,15];
          var dataset = [ 5, 10, 13, 19, 21, 25, 22, 18, 15, 13,
11, 12, 15, 20, 18, 17, 16, 18, 23, 25 ];
          /*d3.select("body").selectAll("div")
            .data(dataset)
            .enter()
            .append("div")
            .style("height", function(d) {
                    return d*5 + "px";
                })
            .attr("class", "bar");
            */

             var w = 500;
             var h = 100;
             var barPadding = 4;
             var svg = d3.select("body")
                .append("svg")
                .attr("width", 520)
                .attr("height", 300)
                .style("border", "1px solid black");

                svg.selectAll("rect")
                    .data(dataset)
                    .enter()
                    .append("rect")
                    .attr("x", function(d, i) {
                        return i * 21; //Bar width of 20 plus 1 for padding
                    })
                    .attr("y", function(d) {
                        return h - d; //Height minus data value
                    })
                    .attr("width",20)
                    .attr("height", function(d) {
                        return d; //This cause issue I guess
                    });
      </script>
  </body>
</html>

代码生成以下输出:

enter image description here

0 个答案:

没有答案