1. 程式人生 > >hicharts堆疊柱狀圖堆疊資料標籤顯示百分比

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中查詢到,或者是我查的不夠細心,不夠認真,沒有查詢到,我從打印出的資訊中捕捉到了相關資訊。實現了相應的功能。