将文本附加到d3js v4中的分组条形图

时间:2017-01-26 10:04:16

标签: javascript d3.js

我试图将文本附加到 d3js v4 中的分组条形图,更具体地说,是对应于每个条形的值。我希望数字显示在条形图内,我无法使其工作。 (像这样:http://bl.ocks.org/ctiml/541d7cc770108ccff79a

但我想让它在 d3js v4 中工作。

这是我的代码,我已经注释了应该附加文字的代码部分

<!DOCTYPE html>
<html>
<meta charset="utf-8">
<head>
<style>
body {
  margin:auto;
  width:1100px;
}
.axis .domain {
  display: none;
}
.bar1 {
  opacity:.9;
}
.yaxis {
  stroke-dasharray: 1 1;
  opacity:.8;
  font-family:arial;
  font-size:10px;
}
path {
  display:none;
}
.baseline {
  stroke:#000;
  stroke-width:1px;
  shape-rendering: crispEdges;
}
</style>
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body><br>
<div id="chart1"></div>
<script>
var margin = {top: 20, right: 110, bottom: 30, left: 40},
    width = 350 - margin.left - margin.right,
    height = 300 - margin.top - margin.bottom,
    formatCount = d3.format("s");

var x0 = d3.scaleBand()
    .rangeRound([0, width])
    .paddingInner(0.1);

var x1 = d3.scaleBand();
    //.padding(0.05);

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

var z = d3.scaleOrdinal()
    .range(["steelblue", "lightblue", "darkorange"]);

var g = d3.select("#chart1").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 + ")");

d3.csv("data.csv", function(d, i, columns) {
    for (var i = 1, n = columns.length; i < n; ++i) d[columns[i]] = +d[columns[i]];
        return d;
    }, function(error, data) {
        if (error) throw error;

    var keys = data.columns.slice(1);

    x0.domain(data.map(function(d) { return d.State; }));
    x1.domain(keys).rangeRound([0, x0.bandwidth()]);
    y.domain([0, d3.max(data, function(d) { return d3.max(keys, function(key) { return d[key]; }); })]).nice();

    g.append("g")
        .attr("class", "yaxis")
        .call(d3.axisLeft(y).ticks(8,"s").tickSize(-width));

    g.append("line")
        .attr("class", "baseline")
        .attr("x1",0)
        .attr("x2",width)
        .attr("y1",y(0))
        .attr("y2",y(0));

    g.append("g")
    .selectAll("g")
    .data(data)
    .enter().append("g")
        .attr("transform", function(d) { return "translate(" + x0(d.State) + ",0)"; })
    .selectAll("rect")
    .data(function(d) { return keys.map(function(key) { return {key: key, value: d[key]}; }); })
    .enter().append("rect")
    .attr("class", "bar1")
        .attr("x", function(d) { return x1(d.key); })
        .attr("y", function(d) { return y(d.value); })
        .attr("width", x1.bandwidth())
        .attr("height", function(d) { return height - y(d.value); })
        .attr("fill", function(d) { return z(d.key); });

    g.append("g")
        .attr("class", "axis")
        .attr("transform", "translate(0," + height + ")")
        .call(d3.axisBottom(x0));

    //g.selectAll(".bar-text")
    //  .data(data)
    //.enter().append("text")
    //  .attr("class",function(d) { return "bar-text " + d.value; })
    //  .attr("x", function(d) { return x1(d.key)+20; })
    //  .attr("y", function(d) { return y(d.value)+10; })
    //.attr("fill","#000")
    //  .text(function(d) { return formatCount(d.value)});

    var legend = g.append("g")
        .attr("font-family", "sans-serif")
        .attr("font-size", 10)
        .attr("text-anchor", "start")
    .selectAll("g")
    .data(keys.slice()) //.reverse
    .enter().append("g")
        .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

    legend.append("rect")
        .attr("x", width + 15)
        .attr("y", 4)
        .attr("width", 12)
        .attr("height", 12)
        .attr("fill", z);

    legend.append("text")
        .attr("x", width + 35)
        .attr("y", 9.5)
        .attr("dy", "0.32em")
        .text(function(d) { return d; });
});
</script>
</body>
</html>

这里是csv格式:

State,Team 1,Team 2,Team 3
2015,2704659,4499890,2159981
2016,2027307,3277946,1420518

1 个答案:

答案 0 :(得分:0)

有很多方法可以做到这一点;我在这里怎么做

首先,保持对组g元素的引用,以便我们可以使用条形附加我们的文本:

var gE = g.append("g")
  .selectAll("g")
  .data(data)
  .enter().append("g")
  .attr("transform", function(d) {
    return "translate(" + x0(d.State) + ",0)";
  });

gE.selectAll("rect")
  .data(function(d) {
  ...

然后使用子选择添加文本:

gE.selectAll("text")
  .data(function(d) {
    return [d['Team 1'], d['Team 2'], d['Team 3']];
  })
  .enter()
  .append("text")
  ...

正在运行的代码为here