Show values on top of bars in a barChart

前端 未结 5 1949
北恋
北恋 2020-12-03 15:47

I have a bar chart with ordinal scale for the x-axis. I want to display the y-values on the top of each bar or in the bottom of each bar. It would be also acceptable to disp

5条回答
  •  臣服心动
    2020-12-03 16:06

    This function will reposition a row chart's labels to the end of each row. A similar technique could be used for a bar chart using the "y" attribute.

    • Labels animate along with the row rect, using chart's transitionDuration
    • Uses chart's valueAccessor function
    • Uses chart's xAxis scale to calculate label position

    rowChart.on('pretransition', function(chart) {
        var padding = 2;
            
        chart.selectAll('g.row > text') //find all row labels
            .attr('x', padding) //move labels to starting position
            .transition() //start transition
            .duration(chart.transitionDuration()) //use chart's transitionDuration so labels animate with rows
            .attr('x', function(d){ //set label final position
                var dataValue = chart.valueAccessor()(d); //use chart's value accessor as basis for row label position
                var scaledValue = chart.xAxis().scale()(dataValue); //convert numeric value to row width
                return scaledValue+padding; //return scaled value to set label position
            });
    });

提交回复
热议问题