Home >Web Front-end >JS Tutorial >How to use stacked charts to display data in Highcharts
How to use stacked charts to display data in Highcharts
Stacked charts are a common way of visualizing data, which can display the sum of multiple data series at the same time. And displays the contribution of each data series in the form of a histogram. Highcharts is a powerful JavaScript library that provides a rich variety of charts and flexible configuration options to meet various data visualization needs. In this article, we will introduce how to use Highcharts to create a stacked chart and provide corresponding code examples.
First, we need to introduce the Highcharts library file. Add the following code in the
tag of the HTML page:<script src="https://code.highcharts.com/highcharts.js"></script>
Then, create a container within the
tag to host the chart. You can use a<div id="chart-container"></div>
Next, we can use JavaScript code to configure and render the chart. To create a stacked chart, we need to use the Stacking property of Highcharts and set it to "normal". At the same time, we also need to specify the name of the data series, the data, and the stacking method. The code is as follows:
Highcharts.chart('chart-container', { chart: { type: 'bar' }, title: { text: '堆叠图表示例' }, xAxis: { categories: ['一月', '二月', '三月', '四月', '五月'] }, yAxis: { min: 0, title: { text: '数值' } }, legend: { reversed: true }, plotOptions: { series: { stacking: 'normal' } }, series: [{ name: '系列一', data: [5, 3, 4, 7, 2] }, { name: '系列二', data: [2, 2, 3, 2, 1] }, { name: '系列三', data: [3, 4, 4, 2, 5] }] });
In the above code, we create a bar chart (type: 'bar') and set the title to "Stacked Chart Example". The category of the x-axis is the month, and the y-axis represents the numerical value. The reversed attribute of the legend is set to true so that the data series are displayed in stacked order. The stacking attribute in plotOptions is set to 'normal', which means that the data series is displayed in a stacked manner. Finally, we specify three data series through the series attribute, including names and corresponding data.
Finally, we just need to place this JavaScript code in the page to ensure that the stacked chart is rendered when the page loads. Once completed, we will have a page with a stacked chart that visually displays the sum and individual contribution of multiple data series.
The above are the specific methods and code examples on how to use stacked charts to display data in Highcharts. With simple configuration and coding, we can easily create an attractive and easy-to-understand stacked chart to better display and analyze data, helping us make more informed decisions.
The above is the detailed content of How to use stacked charts to display data in Highcharts. For more information, please follow other related articles on the PHP Chinese website!