如何在nvd3角度多重条形图中显示每个条形顶部的条形值?

时间:2017-10-15 20:20:18

标签: javascript angularjs nvd3.js

我尝试过使用showValues:在选项中为true,但没有运气。 这是图书馆http://krispo.github.io/angular-nvd3/#/ showValues适用于离散条形图,但不适用于多重条形图。This is the expected output

1 个答案:

答案 0 :(得分:2)

此代码适用于我。

  

1)在图表选项后调用函数( setOnTopLabel(); )    配置。

     

2)在你的js代码中添加这个函数。

function setOnTopLabel() {
            $timeout(function () {
                debugger;
                d3.selectAll('.nv-multibar .nv-group').each(function (group) {
                    debugger;
                    var g = d3.select(this);
                    // Remove previous labels if there is any
                    g.selectAll('text').remove();
                    g.selectAll('.nv-bar').each(function (bar) {
                        var b = d3.select(this);
                        var barWidth = b.attr('width');
                        var barHeight = b.attr('height');

                        g.append('text')
                                // Transforms shift the origin point then the x and y of the bar
                                // is altered by this transform. In order to align the labels
                                // we need to apply this transform to those.
                                .attr('transform', b.attr('transform'))
                                .text(function () {
                                    // Two decimals format
                                    return parseFloat(bar.y);
                                })
                                .attr('y', function () {
                                    // Center label vertically
                                    var height = this.getBBox().height;
                                    return parseFloat(b.attr('y')) - 10; // 10 is the label's magin from the bar
                                })
                                .attr('x', function () {
                                    // Center label horizontally
                                    var width = this.getBBox().width;
                                    return parseFloat(b.attr('x')) + (parseFloat(barWidth) / 2) - (width / 2);
                                }).style("fill", "black").style('stroke-width', "10").style('fill-opacity', "100");
                    });
                });
            }, 1000);
        }