Stacked bar

author(s): Torstein Hønsi

by oysteinmoseng

HTML

<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<script src="https://code.highcharts.com/modules/pattern-fill.js"></script>
<script src="https://code.highcharts.com/modules/accessibility.js"></script>

<figure class="highcharts-figure">
    <div id="container"></div>
</figure>

CSS

.highcharts-figure,
.highcharts-data-table table {
    min-width: 310px;
    max-width: 800px;
    margin: 1em auto;
}

#container {
    height: 400px;
}

.highcharts-data-table table {
    font-family: Verdana, sans-serif;
    border-collapse: collapse;
    border: 1px solid #ebebeb;
    margin: 10px auto;
    text-align: center;
    width: 100%;
    max-width: 500px;
}

.highcharts-data-table caption {
    padding: 1em 0;
    font-size: 1.2em;
    color: #555;
}

.highcharts-data-table th {
    font-weight: 600;
    padding: 0.5em;
}

.highcharts-data-table td,
.highcharts-data-table th,
.highcharts-data-table caption {
    padding: 0.5em;
}

.highcharts-data-table thead tr,
.highcharts-data-table tr:nth-child(even) {
    background: #f8f8f8;
}

.highcharts-data-table tr:hover {
    background: #f1f7ff;
}

JavaScript

// Array of colors to use in High Contrast mode, just copy the default Highcharts patterns for now - possible to define custom ones as well, see https://www.highcharts.com/docs/chart-design-and-style/pattern-fills
const hcColors = Highcharts.patterns.map(p => ({ pattern: Highcharts.merge(p, { color: 'windowText' }) }));

Highcharts.addEvent(Highcharts.Chart, 'afterA11yUpdate', function () {
	if (this.highContrastModeActive && !this.hcColorsOverridden) {
    	this.hcColorsOverridden = true;
        setTimeout(() => {
            this.series.forEach(s => s.update({
                color: hcColors[s.index % hcColors.length]
            }, false));
            this.redraw();        
        }, 0);
    }
});


// Data retrieved from: https://www.uefa.com/uefachampionsleague/history/
Highcharts.chart('container', {
    chart: {
        type: 'column'
    },
    title: {
        text: 'UEFA CL top scorers by season'
    },
    xAxis: {
        categories: ['2020/21', '2019/20', '2018/19', '2017/18', '2016/17']
    },
    yAxis: {
        min: 0,
        title: {
            text: 'Goals'
        }
    },
    legend: {
        reversed: true
    },
    plotOptions: {
        series: {
            stacking: 'normal'
        }
    },
    series: [{
        name: 'Cristiano Ronaldo',
        data: [4, 4, 6, 15, 12]
    }, {
        name: 'Lionel Messi',
        data: [5, 3, 12, 6, 11]
    }, {
        name: 'Robert Lewandowski',
        data: [5, 15, 8, 5, 8]
    }]
});