堆积的条形图没有显示唯一的数据集

时间:2016-06-29 10:58:21

标签: d3.js

我正在尝试使用different countries and its citywise population显示stacked bar chart,但数据集为unique,其中城市和国家/地区彼此独有,我的图表仅显示第一个数据按照代码设置。但是如何使它工作,以便它可以显示每个国家的不同堆积条形的所有数据。以下是我到目前为止所尝试的代码:https://jsbin.com/qopazukahi/edit?html,output

以下是我的数据集:

var data=[
  {
    "Country": "India",
    "Delhi": 310504,
    "Kolkata": 552339,
    "Chennai": 259034,
  },
  {
    "Country": "Australia",
    "Melbourne": 62083,
    "Sydney": 85640,
    "Perth": 42153,
    "Canberra": 74257,
    },
  {
    "Country": "USA",
    "New York": 415910,
    "Miami": 828669,
    "Frankfort": 362642,
    "Portland": 601943,
    "Topeka": 1804762,
  },

];

这是我的完整代码:

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

body {
  font: 10px sans-serif;
}

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

.bar {
  fill: steelblue;
}

.x.axis path {
  display: none;
}

</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>

var margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
    .rangeRoundBands([0, width], .1);

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

var color = d3.scale.ordinal()
    .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);

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

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .tickFormat(d3.format(".2s"));

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 + ")");
var data=[
  {
    "Country": "India",
    "Delhi": 310504,
    "Kolkata": 552339,
    "Chennai": 259034,
  },
  {
    "Country": "Australia",
    "Melbourne": 62083,
    "Sydney": 85640,
    "Perth": 42153,
    "Canberra": 74257,
    },
  {
    "Country": "USA",
    "New York": 415910,
    "Miami": 828669,
    "Frankfort": 362642,
    "Portland": 601943,
    "Topeka": 1804762,
  },

];

  color.domain(d3.keys(data[0]).filter(function(key) { return key !== "Country"; }));

  data.forEach(function(d) {
    var y0 = 0;
    d.ages = color.domain().map(function(name) { return {name: name, y0: y0, y1: y0 += +d[name]}; });
    d.total = d.ages[d.ages.length - 1].y1;
  });

  data.sort(function(a, b) { return b.total - a.total; });

  x.domain(data.map(function(d) { return d.Country; }));
  y.domain([0, d3.max(data, function(d) { return d.total; })]);

  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 Country = svg.selectAll(".Country")
      .data(data)
    .enter().append("g")
      .attr("class", "g")
      .attr("transform", function(d) { return "translate(" + x(d.Country) + ",0)"; });

  Country.selectAll("rect")
      .data(function(d) { return d.ages; })
    .enter().append("rect")
      .attr("width", x.rangeBand())
      .attr("y", function(d) { return y(d.y1); })
      .attr("height", function(d) { return y(d.y0) - y(d.y1); })
      .style("fill", function(d) { return color(d.name); });

  var legend = svg.selectAll(".legend")
      .data(color.domain().slice().reverse())
    .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; });

</script>

2 个答案:

答案 0 :(得分:1)

需要考虑data []数据数组中存在的所有索引如下:

data.forEach(function(d,i) {
            var y0 = 0;
            d.ages = d3.keys(data[i]).filter(function(key) { return  !key.match(/Country/); }).map(function(name) {
                 return {name: name, y0: y0, y1: y0 += +d[name]}; 
            });

以下是工作栏:https://jsbin.com/qopazukahi/edit?html,output

答案 1 :(得分:-1)

难以配置d3.js堆叠图。 在d3.js上有一个名为c3.js的库,它是构建堆积图的简单工具。

var chart = c3.generate({
    data: {
        columns: [
            ['data1', -30, 200, 200, 400, -150, 250],
            ['data2', 130, 100, -100, 200, -150, 50],
            ['data3', -230, 200, 200, -300, 250, 250]
        ],
        type: 'bar',
        groups: [
            ['data1', 'data2']
        ]
    },
    grid: {
        y: {
            lines: [{value:0}]
        }
    }
});

这是它的例子。

如果要旋转轴,请使用

axis: {
        rotated: true
    }

使轴旋转

有关详细信息,请参阅http://c3js.org/