文本在堆叠条形图d3.js的每个条上 [英] Text On each bar of a stacked bar chart d3.js

查看:502
本文介绍了文本在堆叠条形图d3.js的每个条上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在d3.js库中提供的堆叠条形图的每个栏中显示一些文本。



感谢您的帮助。 p>

我已自订范例连结但我没有更改javascript代码



中的任何内容,这里是结果

解决方案

以下是重要的代码:

  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 color(d.name);});

这将每个数据矩形。要添加文本,请按如下所示进行更改:

  var ages_enter = state.selectAll(rect)
.data (function(d){return d.ages;})
.enter();
ages_enter.append(rect)
.attr(width,x.rangeBand())
.attr(y,function(d){return y y1);})
.attr(height,function(d){return y(d.y0) - y(d.y1);})
.style (d){return color(d.name);});
ages_enter.append(text)
.text(function(d){return d3.format(。2s)(d.y1);})
.attr y,function(d){return y(d.y1)+16;})
.style(stroke,'#ffffff');

这存储了一个指向每个数据点调用的enter方法的指针,每个数据点的svg的附加元素。


I would like to have some text in each bar of a stacked bar in stacked bar chart provided in d3.js library.

Thanks for your help.

I have customized the example here link but I have not changed anything else in the javascript code

and here is the result

解决方案

Here is the important piece of code:

  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); });

This binds each data point to the colored rectangles. To add text, change it like this:

  var ages_enter = state.selectAll("rect")
      .data(function(d) { return d.ages; })
    .enter();
  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); });
  ages_enter.append("text")
      .text(function(d) { return d3.format(".2s")(d.y1); })
      .attr("y", function(d) { return y(d.y1)+16; })
      .style("stroke", '#ffffff');

This stores a pointer to the "enter" method that is called for each data point, then adds an additional element to the svg for each data point.

这篇关于文本在堆叠条形图d3.js的每个条上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆