How to correctly centre text element on all bars of a nvd3 bar chart

点点圈 提交于 2019-12-05 19:35:47

Two things make this work.

First, you can't write the labels until the transition is over since the rects won't have their proper height until then.

Second, you can get the rect height by using previousSibling of the text you just added. Putting this together:

d3.select('#chartContainer')
    .append("svg")
    .attr('width', width)
    .attr('height', height)
    .datum(nested_data)
    .transition().duration(1000)
    .call(chart)
    .each("end", function() {
      d3.selectAll(".nv-bar")
        .append("text")
        .attr("x", chart.xAxis.rangeBand() / 4)
        .attr("y", function(d) {
          return d3.select(this.previousSibling).attr('height') / 2;
        })
        .text(function(d) {
          return d.Value
        })
    });

Example here.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!