如何使用D3制作三重条形图?

时间:2015-06-04 19:40:34

标签: javascript d3.js

下面的代码工作得很好,但我想使用另一个数据集。数据集,其中属性是数组本身。它们的结构如下:[年,人口,男人,女人]。年份将是X轴,其他三个将显示为彼此相邻的条形。我如何制作三条形图?从哪里开始?

    <script type="text/javascript">
        //Width and height
        var w = 500;
        var h = 250;
        var barPadding = 5;

        //Dataset
        var dataset = [10027, 10200, 10328, 10436, 10551, 10680, 10822, 10957, 11096, 11278,
                        11417, 11556, 11721, 11890 ];

        //The other dataset
        //[year, population, man, woman]
        //var dataset = [[1950, 10027, 4998, 5029], [1950, 10027, 4998, 5029], [1950, 10027, 4998, 5029], etc];

        //Scale
        var x = d3.scale.ordinal().range([0, w])
        var y = d3.scale.linear().range([h, 0]);

        // Axis
        var xAxis = d3.svg.axis()
            .scale(x)
            .orient("bottom")

        var yAxis = d3.svg.axis()
            .scale(y)
            .orient("left")
            .ticks(10);

        //Create SVG element
        var svg = d3.select("body")
                    .append("svg")
                    .attr("width", w)
                    .attr("height", h);

        svg.selectAll("rect")
           .data(dataset)
           .enter()
           .append("rect")
           .attr("x", function(d, i) {
                return i * (w / dataset.length);
           })
           .attr("y", function(d) {
                return h - (d / 50);
           })
           .attr("width", w / dataset.length - barPadding)
           .attr("height", function(d) {
                return d / 50;
           })
           .attr("fill", function(d) {
                return "rgb(102, 0, 51)";
           });

            svg.append("g")
                .attr("class", "x axis")
                .attr("transform", "translate(0," + h + ")")
                .call(xAxis)
                .style("text-anchor", "end")
                .text("Years");

            svg.append("g")
                .attr("class", "y axis")
                .call(yAxis)
                .append("text")
                .attr("transform", "rotate(-90)")
                .attr("y", 6)
                .attr("dy", "0.5em")
                .style("text-anchor", "end")
                .text("Population in millions");

    </script>

(小问题:为什么我的x轴不出现?)

提前致谢

1 个答案:

答案 0 :(得分:1)

接近你的小问题:你的x轴和y轴被渲染,但在svg可见空间之外。处理此问题的常用方法是在svg中添加margin,并在边距内部使用widthheight呈现图表。这被D3的作者描述为conventional margin

我创建了一个你称之为三重条形图的片段。 此代码是应用于数据集的Bostock的grouped barchart。 我稍微更改了数据集,因此每年都是一个包含属性populationmenwomenyear的对象。通过此设置,可以更轻松地处理值。

分组条形图代码背后的想法是为数据集中的每个对象添加一个组元素,并在该组内呈现条形。 因此,您将数据集绑定到年份组。 在年份选择中,每个元素都绑定到数据集数组中的相应对象。 如果这一切对您没有多大意义,也许您应该阅读Bostock的Let's make a Bar Chart教程。他们对基本步骤给出了很好的概述;)

&#13;
&#13;
var dataset = [{year:1950, population:10000, men:4500, women:5500}, {year:1951, population:10200, men:5000, women:6200}, {year:1952, population:11000, men:6000, women:5000}, {year:1953, population:12000, men:5900, women:6100}];

  // setup conventional margin, see http://bl.ocks.org/mbostock/3019563
  var margin = {top: 20, right: 30, bottom: 30, left: 60},
      width = 700 - margin.left - margin.right,
      height = 400 - margin.top - margin.bottom;

  // accessor functions for the 4 values
  var year = function(d) { return d.year; };
  var population = function(d) { return d.population; };
  var men = function(d) { return d.men; };
  var women = function(d) { return d.women; };
  var valueObject = function(d) { return [{name:"population", value:population(d)},{name:"men", value: men(d)}, {name: "women", value: women(d)}]; };

  var color = d3.scale.ordinal()
    .domain(["population","men","women"])
    .range(["#31a354","#3182bd","#e6550d"]);

  var x0 = d3.scale.ordinal()
      .rangeRoundBands([0, width], .2)
      .domain(dataset.map(year)); // use the year for the xAxis

  var x1 = d3.scale.ordinal()
      .domain(["population","men","women"])
      .rangeRoundBands([0, x0.rangeBand()]);

  var y = d3.scale.linear()
      .range([height, 0])
      .domain([0, d3.max(dataset.map(population))]); // use the population for calculating the maximum value
  
  var xAxis = d3.svg.axis()
      .scale(x0)
      .orient("bottom");
  
  var yAxis = d3.svg.axis()
      .scale(y)
      .orient("left");
  
  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 + ")");

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

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

  var years = svg.selectAll(".year")
      .data(dataset)
      .enter()
    .append("g")
      .attr("class", "year")
      .attr("transform", function(d) { return "translate(" + x0(year(d)) + ",0)"; });

  years.selectAll("rect")
      .data(valueObject)
      .enter()
    .append("rect")
      .attr("width", x1.rangeBand())
      .attr("x", function(d) { return x1(d.name); })
      .attr("y", function(d) { return y(d.value); })
      .attr("height", function(d) { return height - y(d.value); })
      .attr("fill", function(d) { return color(d.name); });

  var legend = svg.selectAll(".legend")
      .data(["population","men","women"])
    .enter().append("g")
      .attr("class", "legend")
      .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

  legend.append("rect")
      .attr("x", width - 18)
      .attr("width", 18)
      .attr("height", 18)
      .style("fill", color);

  legend.append("text")
      .attr("x", width - 24)
      .attr("y", 9)
      .attr("dy", ".35em")
      .style("text-anchor", "end")
      .text(function(d) { return d; });
&#13;
.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
&#13;
&#13;
&#13;