javascript 使用 D3.js 在 rect 上显示文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20626150/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:54:45  来源:igfitidea点击:

Display text on rect using D3.js

javascriptcssd3.js

提问by Preethi

I am developing Normalized stacked bar chart using d3.js,and trying to append a text on rect.It is getting appended when i inspect in browser.But it is not visible.I want something like this,enter image description here

我正在使用 d3.js 开发标准化堆积条形图,并尝试在 rect 上附加一个文本。当我在浏览器中检查时它被附加了。但它不可见。我想要这样的东西,在此处输入图片说明

Here is my code,

这是我的代码,

var margin = {top: 20, right: 100, bottom: 30, left: 40},
    width = 400 - margin.left - margin.right,
    height = 200 - margin.top - margin.bottom;

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

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

var color = d3.scale.ordinal()
    .range(["#404041", "#00adef", "#bbbdc0", "#d1d2d4", "#d3d3d3"]);

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

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

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom + 20)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

d3.json("Nstackedbardata.json", function(error, data) {
  color.domain(d3.keys(data[0]).filter(function(key) { return key !== "State"; }));

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

  data.sort(function(a, b) { return b.ages[0].y1 - a.ages[0].y1; });

  x.domain(data.map(function(d) { return d.State; }));


  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis)
      .style("fill", "#bbbdc0")
      .append("text")
      .attr("class","barChartAxisValue");
    var insertLinebreaks = function (d) {
        var el = d3.select(this);
        var words = d.split(' ');
        el.text('');

        for (var i = 0; i < words.length; i++) {
            var tspan = el.append('tspan').text(words[i]);
            if (i > 0)
                tspan.attr('x', 0).attr('dy', '12');
        }
    };
    svg.selectAll('g.x.axis g text').each(insertLinebreaks);
  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
      .style("fill", "#bbbdc0")
      .append("text")
      .attr("class","barChartAxisValue")
      .attr("transform", "rotate(-90)")
      .attr("x",-70)
      .attr("y", -15)
      .attr("dy", ".71em")
      .style("text-anchor", "middle")
      .text("Percentage");

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


  var sandeep= state.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);})
      .append("text")
      .attr("fill","#fff")
       .style("stroke-width", 1)
      .style({"font-size":"18px","z-index":"999999999"})
      .style("text-anchor", "middle")
      .text(function(d) { return ((d.y1-d.y0)*100).toFixed(0);});


});

回答by musically_ut

You cannot append textelements to rectelements.

您不能将text元素附加到rect元素。

Instead, you should keep them as separate children of the parent g:

相反,您应该将它们作为父级的单独子级保留g

  var sandeep= state.selectAll(".data")
      .data(function(d) { return d.ages; })
      .enter();

   sandeep.append("rect")
      .classed('data', true)
      .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);});

   sandeep
      .append("text")
      .classed('data', true)
      .attr("y", function(d) { return (y(d.y1) + y(d.y0)) / 2; }) // Center text
      .attr("fill","#fff")
      .style("stroke-width", 1)
      .style({"font-size":"18px","z-index":"999999999"})
      .style("text-anchor", "middle")
      .text(function(d) { return ((d.y1-d.y0)*100).toFixed(0);});