hicharts堆叠柱状图堆叠数据标签显示百分比

HTML

<div id="container" style="min-width: 500px; height: 400px"></div>
<script src="./js/highcharts.js"></script>

这个应该都看的懂,没什么疑问,就是一个表格的容器,并且引进了hicharts控件

Js

var chart = Highcharts.chart('container', {
        chart: {
            type: 'column'
        },
        title: {
            text: '堆叠柱形图'
        },
        xAxis: {
            categories: ['苹果', '橘子', '梨', '葡萄', '香蕉']
        },
        yAxis: {
            min: 0,
            title: {
                text: '水果消费总量'
            },
            stackLabels: {  // 堆叠数据标签
                enabled: true,
                style: {
                    fontWeight: 'bold',
                    color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
                },
                formatter: function () {
                    var yData = this.axis.series[1].yData[this.x] / this.total * 100;
                    return yData.toFixed(1) + "%";
                }
            }
        },
        legend: {
            align: 'right',
            x: -30,
            verticalAlign: 'top',
            y: 25,
            floating: true,
            backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || 'white',
            borderColor: '#CCC',
            borderWidth: 1,
            shadow: false
        },
        tooltip: {
            formatter: function () {
                return '<b>' + this.x + '</b><br/>' +
                    this.series.name + ': ' + this.y + '<br/>' +
                    '总量: ' + this.point.stackTotal;
            }
        },
        plotOptions: {
            column: {
                stacking: 'normal',
                dataLabels: {
                    enabled: true,
                    color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white',
                    style: {
                        // 如果不需要数据标签阴影,可以将 textOutline 设置为 'none'
                        textOutline: '1px 1px black'
                    }
                }
            }
        },
        series: [{
            name: '小张',
            data: [5, 3, 4, 7, 2]
        }, {
            name: '小彭',
            data: [2, 2, 3, 2, 1]
        }
        ]
    });

实现效果如下:

这些都好懂,重点是yAxis属性中的enabled属性和formatter函数,需要重点看看:

yAxis: {
            min: 0,
            title: {
                text: '水果消费总量'
            },
            stackLabels: {  // 堆叠数据标签
                enabled: true,
                style: {
                    fontWeight: 'bold',
                    color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
                },
                formatter: function () {
                    var yData = this.axis.series[1].yData[this.x] / this.total * 100;
                    return yData.toFixed(1) + "%";
                }
            }
        }

这里的一些数据没有从api中查询到,或者是我查的不够细心,不够认真,没有查询到,我从打印出的信息中捕捉到了相关信息。实现了相应的功能。

猜你喜欢

转载自blog.csdn.net/hbysj/article/details/82348242