D3.js条形图按百分比表示

时间:2017-03-11 13:07:52

标签: d3.js



var data = [
        {month: 'data', A: 20, B: 5, C: 10},
    ];


    var xData = ["A", "B", "C"];

    var margin = {top: 20, right: 50, bottom: 30, left: 0},
            width = 350 - margin.left - margin.right,
            height = 300 - margin.top - margin.bottom;

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

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

    var color = d3.scale.category20();

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

    var svg = d3.select("#chart").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 dataIntermediate = xData.map(function (c) {
        return data.map(function (d) {
            return {x: d.month, y: d[c]};
        });
    });

    var dataStackLayout = d3.layout.stack()(dataIntermediate);

    x.domain(dataStackLayout[0].map(function (d) {
        return d.x;
    }));

    y.domain([0,
        d3.max(dataStackLayout[dataStackLayout.length - 1],
                function (d) { return d.y0 + d.y;})
        ])
      .nice();

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

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

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

body {
    background-color: #ccc;
    width: 100%;
    font-family: 'Roboto', sans-serif;
    height: 100%;
}

.widget {
    margin: 0 auto;
    width:350px;
    margin-top:50px;
    background-color:#fff;
    -background-color: #222D3A;
    border-radius: 5px;
    box-shadow: 1px 1px 4px 0px rgba(0,0,0,0.3);

}

.header{
    background-color: #eee;
    height:40px;
    color:#555;
    text-align: center;
    line-height: 40px;
    border-top-left-radius: 7px;
    border-top-right-radius: 7px;
    font-weight: 400;
    font-size: 1.5em;
    text-shadow: 1px 1px #fff;
    border-bottom: 1px solid #eaeaea;
}

.chart-container{
    padding:25px;
}

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

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div class="widget">
    <div class="header">Stacked Bar Chart</div>
    <div id="chart" class="chart-container">

    </div>
</div>
&#13;
&#13;
&#13;

我试图使用perctage使用堆叠条创建d3.js。任何人都可以帮助我使用像这个图像的百分比制作这个条形图。演示会非常感激。或者对此的任何参考。

下面的代码是我尝试使用的示例.1显示百分比的单个堆栈条形图。基于值

enter image description here

1 个答案:

答案 0 :(得分:1)

我们首先得到所有酒吧的总和。你的数据显然是35,但让我们不用硬编码就可以了:

var sum = 0;
dataStackLayout.forEach(d => {
    sum += d[0].y
});

然后,我们创建文本元素:

layer.selectAll("foo")
    .data(function(d) {
        return d;
    })
    .enter().append("text")
    .attr("x", function(d) {
        return x(d.x) + x.rangeBand() + 4;
    })
    .attr("y", function(d) {
        return (y(d.y + d.y0) + y(d.y0)) / 2;
    })
    .text(d => format(d.y / sum))

为了定位文本,我们使用相同的数学算法。对于文本的值,我们首先设置D3格式:

var format = d3.format(".2%")

然后我们简单地将每个d.y除以总和。

.text(d => format(d.y / sum))

这是您更新的代码:

var data = [{
  month: 'data',
  A: 20,
  B: 5,
  C: 10
}, ];

var format = d3.format(".2%")


var xData = ["A", "B", "C"];

var margin = {
    top: 20,
    right: 50,
    bottom: 30,
    left: 0
  },
  width = 350 - margin.left - margin.right,
  height = 300 - margin.top - margin.bottom;

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

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

var color = d3.scale.category20();

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

var svg = d3.select("#chart").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 dataIntermediate = xData.map(function(c) {
  return data.map(function(d) {
    return {
      x: d.month,
      y: d[c]
    };
  });
});

var dataStackLayout = d3.layout.stack()(dataIntermediate);

x.domain(dataStackLayout[0].map(function(d) {
  return d.x;
}));

y.domain([0,
    d3.max(dataStackLayout[dataStackLayout.length - 1],
      function(d) {
        return d.y0 + d.y;
      })
  ])
  .nice();

var sum = 0;

dataStackLayout.forEach(d => {
  sum += d[0].y
});

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

layer.selectAll("foo")
  .data(function(d) {
    return d;
  })
  .enter().append("text")
  .attr("x", function(d) {
    return x(d.x) + x.rangeBand() + 4;
  })
  .attr("y", function(d) {
    return (y(d.y + d.y0) + y(d.y0)) / 2;
  })
  .text(d => format(d.y / sum))


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

svg.append("g")
  .attr("class", "axis")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis);
body {
  background-color: #ccc;
  width: 100%;
  font-family: 'Roboto', sans-serif;
  height: 100%;
}

.widget {
  margin: 0 auto;
  width: 350px;
  margin-top: 50px;
  background-color: #fff;
  -background-color: #222D3A;
  border-radius: 5px;
  box-shadow: 1px 1px 4px 0px rgba(0, 0, 0, 0.3);
}

.header {
  background-color: #eee;
  height: 40px;
  color: #555;
  text-align: center;
  line-height: 40px;
  border-top-left-radius: 7px;
  border-top-right-radius: 7px;
  font-weight: 400;
  font-size: 1.5em;
  text-shadow: 1px 1px #fff;
  border-bottom: 1px solid #eaeaea;
}

.chart-container {
  padding: 25px;
}

.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div class="widget">
  <div class="header">Stacked Bar Chart</div>
  <div id="chart" class="chart-container">

  </div>
</div>